4

I've been using following Kotlin extension to add my lifecycle observers:

fun Lifecycle.addObserverUntilDestroy(observer: LifecycleObserver) {
    addObserver(observer)

    addObserver(object : LifecycleObserver {
        @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
        fun onDestroy() {
            removeObserver(this)
            removeObserver(observer)
        }
    })
}

The idea was to automatically remove the observer when the Lifecycle is being destroyed.

So I can call it in Activity's onPostCreate (in this case a Java code but it is the same when calling from Kotlin):

ArchitectureComponentExtensions.addObserverUntilDestroy(getLifecycle(), myViewModel);

And have this code in my ViewModel (a custom one, not the on from Architecture Components):

@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onViewDestroyed() {
    // This is not being called anymore
}

But this stopped working after migrating from:

import android.arch.lifecycle.Lifecycle
import android.arch.lifecycle.LifecycleObserver
import android.arch.lifecycle.LifecycleOwner
import android.arch.lifecycle.OnLifecycleEvent

to:

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.OnLifecycleEvent

Any ideas why this is not working anymore?

Jan Slominski
  • 2,968
  • 4
  • 35
  • 61

0 Answers0