melatonina
03/07/2021, 6:07 PMObservableProperty
with `StateFlow`/`MutableStateFlow`. How can I perform the equivalent of the select
operation with StateFlow
?
The best that came to my mind is something similar to this function:
fun <T, U> CoroutineScope.selectFlow(
stateFlow: StateFlow<T>,
op: (T) -> StateFlow<U>
): StateFlow<U> {
// We can't create a MutableStateFlow without an initial value
val mutableStateFlow = MutableStateFlow(op(stateFlow.value).value)
var job: Job? = null
launch {
stateFlow.collect {
job?.cancel()
job = launch {
op(stateFlow.value).collect {
mutableStateFlow.emit(it)
}
}
}
}
return mutableStateFlow
}
I don't know the StateFlow API very well. Is there a better way?Mark Murphy
03/07/2021, 6:17 PMmelatonina
03/07/2021, 6:18 PMZach Klippenstein (he/him) [MOD]
03/07/2021, 6:36 PMmelatonina
03/07/2021, 6:51 PMmelatonina
03/07/2021, 7:04 PMmelatonina
03/07/2021, 8:41 PMstateIn
, in case I really need a StateFlow
.
Thanks, again.Zach Klippenstein (he/him) [MOD]
03/08/2021, 4:34 PM