What is a good approach to observe a flow like wit...
# compose
b
What is a good approach to observe a flow like with
flowWithLifecycle
and keep na uiState in the viewmodel?
flowWithLifecycle
needs the views lifecycleOwner and should not be placed into the viewmodel. But the content of the observed flow should be placed inside the viewmodel to reduce the composable.
As mentioned in this article by @Manuel Vivo it could sometimes be a use case
m
👋 you have different approaches for this, you could use something like `rememberFlowWithLifecycle`: https://github.com/google/iosched/blob/compose/mobile/src/main/java/com/google/samples/apps/iosched/ui/util/ComposeUtil.kt#L40
Or even the
repeatOnLifecycle
API with a
produceState
. Something like
Copy code
@Composable
fun <T> rememberStateWithLifecycle(
    stateFlow: StateFlow<T>,
    lifecycle: Lifecycle = LocalLifecycleOwner.current.lifecycle,
    minActiveState: Lifecycle.State = Lifecycle.State.STARTED
): State<T> {
    return produceState(
        key1 = stateFlow, key2 = lifecycle, key3 = minActiveState,
        initialValue = stateFlow.value
    ) {
        lifecycle.repeatOnLifecycle(minActiveState) {
            stateFlow.collect {
                this@produceState.value = it
            }
        }
    }
}
b
But these are both for placing them inside a composable. I'm looking for an approach to observe it inside the viewmodel. So I can emit the uiState from the viewmodel to the composable with all required states in it.
m
Those functions are just to collect flows in the UI. If you want to collect a flow in the VM, just call
collect
with a coroutine launched in a VM scope
âž• 1
m
if you want to just convert to UiState, you can use
.map { }
on StateFlow but if you want to do something else with the data you can go ahead with
collect
s
Hmm but why would we want to use this over a simple
.collectAsState()
when we already have a
StateFlow
and not a raw
Flow
? Are there specific use-cases we should be wary of?