without having to use a suspend function. Of course, then you will have to duplicate (or extra a helper method) to get the same result as from the combine method
Joost Klitsie
06/11/2021, 12:09 PM
Copy code
val firstField: StateFlow<String> = MutableStateFlow("a")
val secondField: StateFlow<Int> = MutableStateFlow(11)
val scope = CoroutineScope(Dispatchers.Default)
val canDoSomethingScary: StateFlow<Boolean> = scope.combineStates(firstField, secondField) { first, second ->
first.isNotBlank() && second > 0 && second < 10
}
fun <T, U, R> CoroutineScope.combineStates(
stateFlow1: StateFlow<T>,
stateFlow2: StateFlow<U>,
started: SharingStarted = SharingStarted.Eagerly,
suspendTransform: suspend (T,U) -> R = { arg1, arg2 -> transform(arg1, arg2) },
transform: (T, U) -> R) =
combine(stateFlow1, stateFlow2, suspendTransform).stateIn(this, started, transform(stateFlow1.value, stateFlow2.value))
k
Kirill Vasilenko
06/11/2021, 1:23 PM
The main idea is to avoid being suspended and couroutine scopes where it is possible. Making view models should be as simple as possible.
Kirill Vasilenko
06/11/2021, 1:24 PM
I will remove the post everywhere except #coroutines channel. So please ask your questions there or, that would be better, on GitHub.