What would be the best practice in jetpack compose...
# compose
a
What would be the best practice in jetpack compose to react to the application being paused, such as the user swapping to another application? This would be useful such as when the application is playing audio, you don't want the audio to continue playing when the app is in the background. I know we can override onPause() in the main activity, but how can we aim to let the rest of the application know that it is paused?
j
I would suggest a DisposableEffect for this use case
a
From my testing, disposable effect does not take into effect when the application is send to the background, so I have come looking for an alternative
n
Copy code
val lifecycleOwner = LocalLifecycleOwner.current
DisposableEffect(lifecycleOwner) {
    val observer = LifecycleEventObserver { _, event ->
        if (event == Lifecycle.Event.ON_PAUSE) {
            // onPause
        } else if (event == Lifecycle.Event.ON_RESUME) {
            // onResume
        }
    }
    lifecycleOwner.lifecycle.addObserver(observer)
    onDispose {
        lifecycleOwner.lifecycle.removeObserver(observer)
    }
}
👍 1
a
Thank you very much, this works perfectly!