Landry Norris
05/20/2022, 6:50 PMMichael Marshall
05/20/2022, 7:59 PMLandry Norris
05/20/2022, 8:03 PMdata class UIState(val controllers: List<Controller>, currentController: Controller? = controllers.firstOrNull())
and a class like
class Controller {
val positionFlow: Flow<Double> = MutableStateflow(0.0)
}
Whenever the position changes, I call positionFlow.update { value }
In my code, I have val state = MutableStateFlow(UIState(...))
. I want to collect the currentController’s positionFlow, but I want it to update whenever I change currentControllerstate.collect { currentState ->
currentState.currentController.positionFlow?.collect { position ->
//Code that uses position
}
}
Michael Marshall
05/23/2022, 4:54 PMfun reactToControllerAndPositionChanges() {
// I assume you have some scope
val scope = CoroutineScope(Dispatchers.Default)
// Old way
scope.launch {
state.collect { currentState ->
currentState.currentController?.positionFlow?.collect { position ->
positionCode(position)
}
}
}
// New way
state
.flatMapLatest { state ->
state.currentController?.positionFlow ?: emptyFlow()
}
.onEach(::positionCode)
.launchIn(scope)
}
private fun positionCode(position: Double) {
TODO()
}
ControllerState
) you could instead just use val state = MutableStateFlow(ControllerState(...)
and switch out the controllers info in the business logic behind the scenes instead.data class ControllerState(val position: Double)
and update the whole state
whenever the position changesLandry Norris
05/23/2022, 5:28 PMMichael Marshall
05/23/2022, 5:33 PMLandry Norris
05/23/2022, 5:34 PMMichael Marshall
05/24/2022, 6:56 PMLandry Norris
05/24/2022, 6:58 PMMichael Marshall
05/24/2022, 7:04 PMLandry Norris
05/24/2022, 7:06 PMMichael Marshall
05/24/2022, 7:07 PM