Is there a way to tie this knot? ``` var lifecycleObserver: LifecycleObserver lifecyc...
r
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
What is the knot 🪢
r
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
Lifecycle keeps weak references? Why you need that? Not duplicating observer instances
r
Aye, works for me then
👍 1
i
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
Neato, thanks!