Bino
02/22/2022, 8:19 AMflowWithLifecycle
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
Manuel Vivo
02/22/2022, 8:28 AMrepeatOnLifecycle
API with a produceState
. Something like
@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
}
}
}
}
Bino
02/22/2022, 8:34 AMManuel Vivo
02/22/2022, 9:37 AMcollect
with a coroutine launched in a VM scopems
02/22/2022, 12:04 PM.map { }
on StateFlow but if you want to do something else with the data you can go ahead with collect
Stylianos Gakis
03/03/2022, 9:56 PM.collectAsState()
when we already have a StateFlow
and not a raw Flow
? Are there specific use-cases we should be wary of?