Hello. I'm trying to share some ViewModels between...
# android
m
Hello. I'm trying to share some ViewModels between the JavaFX version of my application, and the Android version. For this purpose, I'm replacing JavaFX
ObservableProperty
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:
Copy code
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?
m
FWIW, this might be better for the #coroutines channel
m
Thanks, @Mark Murphy. I was indeed looking for a more appropriate channel.
👍🏻 1
z
That looks like a flatMapLatest
💯 1
m
Yes, it looks like that. Thank you very much, @Zach Klippenstein (he/him) [MOD]!
@Zach Klippenstein (he/him) [MOD] The only problem is that it produces a Flow, not a StateFlow. I'll check if that's actually a problem or not.
So far I didn't notice any repercussion. I guess I can use
stateIn
, in case I really need a
StateFlow
. Thanks, again.
z
Yep, you’ll find that none of the operators on StateFlow produce a StateFlow, so you’ll always need to use stateIn if you need that. The reason is a bit more complicated than you might think