Hi! Is this the best way to get `onStart` events ...
# compose
a
Hi! Is this the best way to get
onStart
events in compose? Code in 🧵
Copy code
@Composable
 fun MyComposable(
   myViewModel: MyViewModel = getViewModel(),
 ) {
   DisposableEffect("") {
     val observer = LifecycleEventObserver { _, event ->
       alertsViewModel.onLifecycleEvent(event)
     }
     lifecycle.addObserver(observer)
     onDispose { lifecycle.removeObserver(observer) }
   }
   ...
 }
 
 class MyViewModel: ViewModel() {
   fun onLifecycleEvent(event: Lifecycle.Event) {
     when (event) {
       Lifecycle.Event.ON_START -> {
         // track "screen"
       }
     }
   }
 }
m
where is “lifecycle coming from?
a
from activity
m
To be honest, IMHO, i don’t view a Lifecycle observer as the job of a composition. In my mind, i would pass two lambda functions to to your composable to call.
Copy code
@Composable
fun MyComposable(
     onStart: () -> Unit,
     onStop: () -> Unit
) {
    DisposableEffect {
       onStart()
       onDispose { onStop() }
    }
}
a
but
DisposableEffect
is more like..
onCreate()
?
m
that said, composables don’t follow the activity or fragment directly. They have their own lifecycle, which may or may not compose and dispose with the container.
a
yeah...
the problem is that our data team needs events send at
onStart()
m
Copy code
A side effect of composition that must run for any new unique value of key1 and must be reversed or cleaned up if key1 changes or if the DisposableEffect leaves the composition.
Basically think of it as a way (assuming a constant key) for you to register callbacks for first composition, and disposal.
a
This is exactly the example in the doc.
☝️ 1
m
It’s not analagous.
Ok. So what they are doing is keying the disposable to the lifecycle owner (which makes it constant), and then putting an effect on the outermost composition. The outermost composition tends to have a lifecycle consistent with the container activity or fragment.
But keep in mind, it’s only appropriate for that use case in my opinion
If you were to nest this composition inside of some other composition you would get some very unintended side effects.
also keep in mind they are passing the event function “onStart” and “onStop” as a lambda function. Generally your composables shouldn’t rely on view models (again my own opinion)
i
If you want onStart and onStop, you must follow the docs and actually observe the Lifecycle - disposal is absolutely not the same thing at all. For example, when you hit the Home button and go back to your launcher, your composables are not disposed at all - the only change is that the Lifecycle is stopped.
👍 1
I'd probably keep analytics tracking close to the root of your composable hierarchy or the root of your screen (if you're using Navigation Compose, which provides every screen its own Lifecycle)
👍 1