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

Colton Idle

08/23/2022, 8:12 AM
Is there a less verbose way of writing this?
Copy code
val lifecycle = LocalLifecycleOwner.current.lifecycle
DisposableEffect(lifecycle) {
  val observer = LifecycleEventObserver { _, event ->
    if (event == Lifecycle.Event.ON_RESUME) {
      vm.doThing()
    }
  }
  lifecycle.addObserver(observer)
  onDispose { lifecycle.removeObserver(observer) }
}
vm.doThing() launches a coroutine in this case, but in other cases where I collect a flow I just write
Copy code
vm.someFlow.collectAsStateWithLifecycle()
and I'm curious if I could somehow reuse this collectAsStateWithLifecycle function that's provided to us.
t

Tolriq

08/23/2022, 8:48 AM
You can easily extract that into a reusable code.
Copy code
@Composable
fun StartOnResume(block : suspend () -> Unit) {
... your helper
}
Then where wanted just StartOnResume { vm.doThing() }
c

Colton Idle

08/23/2022, 8:58 AM
Thanks. I didn't know if there was maybe something out of the box i was missing.
f

Francesc

08/23/2022, 4:04 PM
there is an artifact that lest you observe a
LiveData
as state, similar to what you can do with `flow`s, would that work for you?
i

Ian Lake

08/23/2022, 5:48 PM
FWIW, we're tracking adding exactly this kind of helper for triggering a side-effect when the Lifecycle changes in https://issuetracker.google.com/235529345
7 Views