Skip to content
DeveloperMemos

Listening to Lifecycle Events in Jetpack Compose

Android, Jetpack, Compose, Kotlin1 min read

Here's a quick post about how you can listen to lifecycle events like onResume or onPause in Jetpack Compose.

To preface this post, typically you don't really have any need to listen to lifecycle events in Compose - but there can be some edge cases where it is necessary. Especially if you are slowly migrating a project to Compose and you have some pre-existing logic that involves lifecycle events somehow.

OnLifecycleEvent Composable

Here's a Composable that you can add to your project specifically to listen for lifecycle events:

1@Composable
2fun OnLifecycleEvent(
3 lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current,
4 onEvent: (owner: LifecycleOwner, event: Lifecycle.Event) -> Unit
5) {
6 DisposableEffect(lifecycleOwner) {
7 val lifecycle = lifecycleOwner.lifecycle
8 val observer = LifecycleEventObserver { owner, event ->
9 onEvent.invoke(owner, event)
10 }
11
12 lifecycle.addObserver(observer)
13 onDispose {
14 lifecycle.removeObserver(observer)
15 }
16 }
17}

I'll briefly explain what this is doing. It works a little like how a hook works in React. You use DisposableEffect which will run some code on launch(or specifically when lifecycleOwner changes) and then it will run the code in onDispose on teardown. So in summary you hook into LifecycleOwner and add an observer(which passes on events to the callback onEvent) then remove it on tear down.

How to use it

Here's an example of how you could use OnLifecycleEvent inside another Composable:

1@Composable
2fun Container() {
3 OnLifecycleEvent(onEvent = { _, event ->
4 if (event == Lifecycle.Event.ON_RESUME) {
5 // Do something here
6 }
7 })
8
9 Text("Example")
10}

The example above specifically detects onResume(Lifecycle.Event.ON_RESUME) but you could listen to onPause(Lifecycle.Event.ON_PAUSE) or anything else you want to:

1@Composable
2fun Container() {
3 OnLifecycleEvent(onEvent = { _, event ->
4 if (event == Lifecycle.Event.ON_PAUSE) {
5 // Do something here
6 }
7 })
8
9 Text("Example")
10}