https://kotlinlang.org logo
#compose
Title
# compose
b

Bino

02/22/2022, 8:19 AM
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

Manuel Vivo

02/22/2022, 8:28 AM
👋 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

Bino

02/22/2022, 8:34 AM
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

Manuel Vivo

02/22/2022, 9:37 AM
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

ms

02/22/2022, 12:04 PM
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

Stylianos Gakis

03/03/2022, 9:56 PM
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?
43 Views