paul_f
paul_f

Reputation: 1375

Removing a live data Observer create inside a closure

I am having a problem removing live data observer created inside a closure.

The Observer is create like so:

recordingListener.startRecording() {ID ->
        this.ID = ID
        locationViewModel.getAllByID(ID).observe(this, android.arch.lifecycle.Observer {locations ->
            myViewService.showDataOnMap(locations!!)
        })
    }

I am trying to remove it like so:

locationViewModel.getAllByID(ID).removeObservers(this)

But it seems the observer is persisting even after removeObserver is called. My thought is that the issue is caused by the fact that the observer is created inside a closure, or else perhaps I am doing something else wrong.

Upvotes: 2

Views: 6067

Answers (1)

paul_f
paul_f

Reputation: 1375

The issue is in subsequent calls to locationViewModel I was making more calls the same ID. This prevents the locationViewModel Observer from being removed.

To solve the problem, I am now using a LiveData extension ObserveOnce, in subsequent calls to locationViewModel. All it does is just makes managing calls to the ViewModel that only require a single response a bit easier.

I can't speak to whether it is the best practice or not, and its need probably stems from bad architecture in my app, but for this it works and works well so happy days, here is the Observe once code:

fun <T> LiveData<T>.observeOnce(lifecycleOwner: LifecycleOwner, observer: Observer<T>) {
    observeForever(object : Observer<T> {
        override fun onChanged(t: T?) {
            observer.onChanged(t)
            removeObserver(this)
        }
    })
} 

I'm calling it like this:

locationViewModel.getAllByID(ID).observeOnce(this, Observer {locations ->

})

Upvotes: 1

Related Questions