https://kotlinlang.org logo
Title
c

Chris Fillmore

11/18/2021, 10:29 PM
I have a utility function which `remember`s a call to
flowWithLifecycle
, and I’m wondering if it’s wise (some code in thread)
@Composable
fun <T> Flow<T>.lifecycleAware(
  minActiveLifecycleState: Lifecycle.State = Lifecycle.State.STARTED,
): Flow<T> {
  val lifecycleOwner = LocalLifecycleOwner.current
  return remember(this, lifecycleOwner) {
    flowWithLifecycle(lifecycleOwner.lifecycle, minActiveLifecycleState)
  }
}
I then have another function which calls this along with
collectAsState
@SuppressLint("FlowOperatorInvokedInComposition")
@Composable
fun <T> Flow<T>.lifecycleCollectAsState(
  initial: T,
  minActiveLifecycleState: Lifecycle.State = Lifecycle.State.STARTED,
): State<T> {
  return lifecycleAware(minActiveLifecycleState).collectAsState(initial)
}
However as you see I have to suppress
FlowOperatorInvokedInComposition
. I’m not sure if this poses a problem or not.
Further, I have another one for `StateFlow`s which uses
value
as the initial value
@SuppressLint("StateFlowValueCalledInComposition")
@Composable
fun <T> StateFlow<T>.lifecycleCollectAsState(
  minActiveLifecycleState: Lifecycle.State = Lifecycle.State.STARTED,
): State<T> {
  return lifecycleCollectAsState(value, minActiveLifecycleState)
}
But as you can see I am now suppressing
StateFlowValueCalledInComposition
here
I think (perhaps wrongly) that suppressing these errors is ok, because I am `remember`ing the underlying Flow, keyed with the upstream flow and the LifecycleOwner.
Is this wrong?
a

Adam Powell

11/18/2021, 11:10 PM
at a glance it looks like the lint warning is a bit overzealous, cc @Louis Pullen-Freilich [G]
looks fine to me with the exception that you're not using
minActiveLifecycleState
as a
remember
key; if that changes, a previously remembered flow won't.
l

Louis Pullen-Freilich [G]

11/18/2021, 11:22 PM
Yeah, for anything similar to
collectAsState
in nature this is a false positive / safe to ignore, I don’t think there’s a way we can avoid warning here short of removing the lint check - and I think basically every other case that it catches is worth catching
👍 1
a

Adam Powell

11/18/2021, 11:49 PM
we could probably skip warning on flow extension functions that are marked
@Composable
👍 1
l

Louis Pullen-Freilich [G]

11/19/2021, 12:06 AM
Yeah, could work.
c

Chris Fillmore

11/22/2021, 5:15 PM
Thanks for responding! And thanks for the advice. Looks like I’ll keep them suppressed for now and add
minActiveLifecycleState
as a key