https://kotlinlang.org logo
#android
Title
# android
r

reactormonk

09/20/2023, 5:34 PM
Is there a way to tie this knot?
Copy code
var lifecycleObserver: LifecycleObserver
        lifecycleObserver = LifecycleEventObserver { _, event ->
            when (event) {
                Lifecycle.Event.ON_START -> player.play()
                Lifecycle.Event.ON_STOP -> player.pause()
                Lifecycle.Event.ON_DESTROY -> {
                    player.release()
                    lifecycleOwner.lifecycle.removeObserver(lifecycleObserver)
                }
                else -> {}
            }
        }
        lifecycleOwner.lifecycle.addObserver(lifecycleObserver)
p

Pablichjenkov

09/20/2023, 6:00 PM
What is the knot 🪢
r

reactormonk

09/20/2023, 6:01 PM
Copy code
var removeObs = {}
        val lifecycleObserver = LifecycleEventObserver { _, event ->
            when (event) {
                Lifecycle.Event.ON_START -> player.play()
                Lifecycle.Event.ON_STOP -> player.pause()
                Lifecycle.Event.ON_DESTROY -> {
                    player.release()
                    removeObs()
                }
                else -> {}
            }
        }
        removeObs = {lifecycleOwner.lifecycle.removeObserver(lifecycleObserver)}
        lifecycleOwner.lifecycle.addObserver(lifecycleObserver)
p

Pablichjenkov

09/20/2023, 6:06 PM
Lifecycle keeps weak references? Why you need that? Not duplicating observer instances
r

reactormonk

09/20/2023, 6:06 PM
Aye, works for me then
👍 1
i

Ian Lake

09/20/2023, 7:11 PM
All observers are automatically removed when the Lifecycle goes through
ON_DESTROY
, so you don't need to manually remove them at all
👍 2
That was one of the behavior changes in Lifecycle 2.5: https://developer.android.com/jetpack/androidx/releases/lifecycle#2.5.0
r

reactormonk

09/20/2023, 7:13 PM
Neato, thanks!
2 Views