Hi all! Has anyone ever used `LifecycleObserver`s ...
# android
t
Hi all! Has anyone ever used `LifecycleObserver`s for running
suspend
functions or collecting
Flows
via
lifecycleOwner
-> scope?
👌 2
both available in the latest lifecycle-ktx alpha releases
t
Great! Thanks Adam. I’m assuming then that such a
LifecycleObserver
would only be interested in the
onCreate()
lifecycle method from which to launch coroutines? Otherwise, hooking into
onStart()
etc seems awkward/redundant
On the flipside,
LifecycleObserver
offers nice dependency inversion and direct access to the
LifecycleOwner
, but I can imagine it’d be nice to be able to inject/provide via DI some scoped
Lifecycle
for such “worker” classes that launch coroutines for specific/contained work. Not sure if that’s an anti-pattern, though 🤔
a
The
lifecycleScope
extension on LifecycleOwner is exactly that, it spans onCreate => onDestroy: https://developer.android.com/reference/kotlin/androidx/lifecycle/package-summary#lifecyclescope
repeatOnLifecycle
runs one iteration of the given body block each time the lifecycle raises up to at least a given state, i.e. started: https://developer.android.com/reference/kotlin/androidx/lifecycle/package-summary#repeatonlifecycle
t
👍🏼 Even better. So then `LifecycleObserver`s are not really needed any more when doing work via coroutines. Just having a handle to the
Lifecycle
is enough given all these extension functions that are available.
a
Not directly but all of these are using `LifecycleObserver`s under the hood, they're just nicer to use this way
1
🙏🏼 1