<@UDFLD19DL> Re: <https://medium.com/androiddevel...
# compose
j
@Manuel Vivo Re: https://medium.com/androiddevelopers/a-safer-way-to-collect-flows-from-android-uis-23080b1f8bda Was wondering if a similar utility composable function would eventually find its way in compose in order to reduce boilerplate even further:
Copy code
@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.
👍 1
a
We've had a lot of discussion around it. I'm still sort of on the fence. Part of the issue is that you kind of have to do all of this for any operator you want to use if you go for this style, and then you're saving off every intermediate link in the assembled flow chain into the composition for no real good reason.
The scalable way to go about this is something like:
Copy code
val currentValue by produceState(initialValue, myFlow, myLifecycle) {
  myFlow.map { doStuffTo(it) }
    .filter { it.foo == somethingToMatch }
    .flowWithLifecycle(myLifecycle)
    .collect { value = it }
}
👍 2
👍🏻 1
wrapping every last operator in a compose version leads to a lot of API surface really quickly
☝🏼 1
👍 1
not to mention a treadmill of trying to keep up with new flow operators added
👍 1
I think we might be more likely to add something like a
Copy code
suspend fun Flow<T>.collectTo(target: MutableState<T>) {
  collect { target.value = it }
}
to make the above turn into
Copy code
.collectTo(this)
but that's not that much shorter
m
Thanks for the reply Adam! Agreed! We shouldn’t have a
rememberX
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!
☝🏼 1
j
Cool, thanks for sharing your internal thoughts. It’s always enlightening.