在 Kotlin 中使用状态机并发送更新

问题描述 投票:0回答:1

我创建了一个状态机,使用

KStateMachine
定义了它的状态、事件和转换。当事件发送到状态机时,状态会相应改变。

由于UI与状态机无关,所以仍然需要根据状态机的当前状态来显示元素

在下面的示例中,我如何通知 UI 状态机的状态已更改?

@Singleton
class StateManager() : IStateManager {
    private var stateMachine: StateMachine? = null

    init {
        runBlocking {
            startupMachine()
        }
    }
    
    private suspend fun startupMachine() {
        val scope = CoroutineScope(Dispatchers.IO)
        stateMachine = createStateMachine(scope) {
            addInitialState(State.Initializing)

            addState(State.Starting) {
                transition<Event.Initializing> {
                    targetState = State.Initializing
                }
            }

            addState(State.Initializing) {
                transition<Event.Initialized> {
                    targetState = State.Initialized
                }
            }

            onStateEntry { state, _ ->
                println("Received new state of $state")
            }
        }
    }

    override suspend fun processEvent(event: StateEvent) {
        stateMachine!!.processEvent(event)
    }
}
java kotlin observable state-machine
1个回答
0
投票

根据文档,您将 StateFlow 作为属性公开:

class StateManager() : IStateManager {
    private val _stateFlow: MutableStateFlow(State.Default)
    val stateFlow = _stateFlow.asStateFlow()
    ...

您可以在任何您关心的地方收集它(在本例中是您的 UI),再次根据文档

class YourUi {
   fun startCollecting() {
       myStateManager.stateFlow.collect {
           updateUiWith(it)
       }
   }
}

您可以通过更新来“触发事件”:

onStateEntry { state, _ ->
    println("Received new state of $state")
    _stateFlow.value = state
}
© www.soinside.com 2019 - 2024. All rights reserved.