Skip to content Skip to sidebar Skip to footer

Android Lifecycle Library: Cannot Add The Same Observer With Different Lifecycles

I have an app I'm working on that's using the lifecycle library but I'm getting an IllegalArgumentException that says 'Cannot add the same observer with different lifecycles' I onl

Solution 1:

In my case the problem was at lambda method of observer is empty. I just tried to add something to it and problem was solved. For example:

gpsState.observe(this, (state) -> {
                Log.d(this.getClass().getSimpleName(), BaseNavigationActivity.this.toString());

});

Most likely that JVM define anonymous classes that use only static references and for such cases it become kinda singleton, so you will have same instance all the time you reference such class.


Solution 2:

As thehebrewhammer said in a comment, I had the same issue because of Kotlin SAM-Lambda optimization.

viewModel.myLiveData.observe(this, Observer {
    NavigationBackEvent().post()
})

This SAM-Lambda doesn't access anything of the class and will be compiled to a singleton for optimization.
I changed it to a class initialization for forcing new instance at each run:

viewModel.myLiveData.observe(this, MyObserver())

and

class MyObserver : Observer<MyType?> {
    override fun onChanged(it: MyType?) {
        NavigationBackEvent().post()
    }
}

Solution 3:

I had the same issue, these lines of code solved it:

sharedViewModel.getFriendsList().observe(this, object: Observer<ArrayList<User>> {
    override fun onChanged(t: ArrayList<User>?) {
        CurrentUser.friendsList = t
    }
})

Solution 4:

Based on previous responses all you need to do is create a new Object every time you subscribe your observer.

gpsState.observe(this, object: Observer<GpsState> {
    // ...
});

PD: I assumed that GpsState is the data type you want observe. In my case was Long


Post a Comment for "Android Lifecycle Library: Cannot Add The Same Observer With Different Lifecycles"