julioromano
03/24/2021, 9:40 PM@Composable
fun <T> Flow<T>.rememberWithLifecycle(
minActiveState: Lifecycle.State = Lifecycle.State.STARTED
): Flow<T> {
val lifecycleOwner = LocalLifecycleOwner.current
return remember(this, lifecycleOwner) {
flowWithLifecycle(lifecycleOwner.lifecycle, minActiveState)
}
}
P.S. Please read the thread to get an understanding of why this approach is probably a not very good idea.Adam Powell
03/25/2021, 1:28 AMAdam Powell
03/25/2021, 1:30 AMval currentValue by produceState(initialValue, myFlow, myLifecycle) {
myFlow.map { doStuffTo(it) }
.filter { it.foo == somethingToMatch }
.flowWithLifecycle(myLifecycle)
.collect { value = it }
}
Adam Powell
03/25/2021, 1:32 AMAdam Powell
03/25/2021, 1:32 AMAdam Powell
03/25/2021, 1:36 AMsuspend fun Flow<T>.collectTo(target: MutableState<T>) {
collect { target.value = it }
}
to make the above turn into
.collectTo(this)
but that's not that much shorterManuel Vivo
03/25/2021, 6:57 AMrememberX
for any potential operator that could be applied to a Flow. But there are other alternatives.
We definitely don’t want to include something like this in collectAsState
as it should be platform independent. However, we could add a new API (when possible) for Android apps and call it something like collectAsStateWithLifecycle
? May be too verbose and could create confusion? Who knows, we need to think more about it 🙂 thanks!julioromano
03/25/2021, 8:00 AM