My google-fu is failing me. What was the "new" way...
# compose-android
c
My google-fu is failing me. What was the "new" way to observe android lifecycle events like onCreate, onStart, etc in compose. I used to use disposableEffect, but there was some artifact that was updated with this I recall...
p
I don't think it is out yet, unless it was really recent
c
too many release notes ive read. i forget whats what. 😂
😁 1
i
It was the 2.7.0-alpha01 release of
lifecycle-runtime-compose
that has the new
LifecycleEventEffect
for a single event and
LifecycleStartEffect
/
LifecycleResumeEffect
for a disposable effect style pair of events: https://developer.android.com/jetpack/androidx/releases/lifecycle#2.7.0-alpha01
c
Do you by chance know if there are any sample usages of this. I can't seem to get LifecycleStartEffect to compile. feel like im mis-understanding something here
i
You know how
DisposableEffect
needs to end in a
onDispose
block?
LifecycleStartEffect
needs to end in a
onStopOrDispose
block - that's the "pair of events" I mentioned: https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:lifecycl[…]idx/lifecycle/compose/samples/LifecycleComposeSamples.kt;l=92
❤️ 4
🙏 3
🙏🏾 1
c
I'm going to test this out myself... but figured I'd ask since we have the thread going anyway. Is this
Copy code
LifecycleStartEffect {
            dataAnalytics.startTimeTracking()

            onStopOrDispose {
                timeTracker.stopTimeTracking()
            }
        }
equivallent to this?
Copy code
LifecycleEventEffect(Lifecycle.Event.ON_START){
dataAnalytics.startTimeTracking()
  }

LifecycleEventEffect(Lifecycle.Event.ON_STOP){
dataAnalytics.stopTimeTracking()
  }
i
The
OrDispose
part of
onStopOrDispose
should be a clue on where they differ: if the
LifecycleStartEffect
is removed from composition (say, it is inside an if statement that changes from true to false) before the Lifecycle is stopped, the
onStopOrDispose
block will still fire, ensuring the cleanup of whatever you did before that block is guaranteed to run if you ever got STARTED. Having two separate blocks won't have that property - if you put your code in separate
LifecycleEventEffect
blocks, there's no coupling between them and thus no guaranteed cleanup
👍 2
m
@Ian Lake The
onStopOrDispose
gets called twice (if you navigate out of a screen, it gets fired both for the STOP lifecycle event, and again for being disposed) which is a problem if the cleanup is not idempotent. Is this intended? In the above example
stopTimeTracking()
would get called twice which depending on the implementation may be a problem, where having the two separate `LifecycleEventEffect`s doesn't have that problem.
i
It should only fire once, please file a bug if you're seeing something different: https://issuetracker.google.com/issues/new?component=413132
👍 1
m