Slackbot
06/11/2021, 8:47 AMJoost Klitsie
06/11/2021, 11:54 AMstateIn
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 methodval 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))
Kirill Vasilenko
06/11/2021, 1:23 PM