natario1
03/14/2023, 12:16 PMclass Processor {
private val condition1 = MutableStateFlow(false)
private val condition2 = MutableStateFlow(false)
private suspend fun process(): Processed { ... }
init {
someScope.launch {
combine(condition1, condition2) { a, b -> a || b }
.collectLatest { process() }
}
}
fun setCondition1() { condition1.value = true }
fun setCondition2() { condition2.value = true }
}
When the user changes one of the conditions, I would like to
• know if this change did not trigger a process()
(for example, throw if not)
• return something like a Deferred<Processed>
to be (optionally) awaited.
Does anyone have any idea on how to achieve this?Dmitry
03/14/2023, 12:29 PMStateFlow
in context of the ViewModel
. For me it would be more natural to keep your state within separate data class like:
data class DeputiesModel(
override var isLoading: Boolean = false,
override val errors: List<String> = emptyList<String>(),
var deputies: List<Deputy> = emptyList()
) : Model
and then expose it as a StateFlow:
private val state: MutableStateFlow<DeputiesModel> = MutableStateFlow(DeputiesModel())
val uiState: StateFlow<DeputiesModel> = state
.asStateFlow()
.stateIn(viewModelScope, SharingStarted.Eagerly, state.value)
In this case each change within model will trigger all listeners/subscribers and you could check the actual result.
For extra control I added a flag which defines state of the model (it was convenient for Composable screens in Android).
That's how I would do the similar use case in context of Android development.