Android: Kotlin LiveData/MutableLiveData custom observer
How to solve the problem of unsubscribing observer after getting update once
LiveData
is an observable data holder class. Unlike a regular observable, LiveData is lifecycle-aware, meaning it respects the lifecycle of other app components, such as activities, fragments, or services. This awareness ensures LiveData only updates app component observers that are in an active lifecycle state.
How it works: LiveData considers an observer, which is represented by the Observer
class, to be in an active state if its lifecycle is in the STARTED
or RESUMED
state. LiveData only notifies active observers about updates. Inactive observers registered to watch LiveData
objects aren't notified about changes.
A simple example could be like this:
val data = MutableLiveData<String>("abc")
data.observe(this, Observer {
val value = it ?: return@Observer
})
Above observer will keep on observing data for updates whenever activity/fragment goes to onStart or onResume.
Now, what if we would like to unsubscribe observer after non-null successful update and we would like to have reusable code? Let’s create an extension function:
fun <T> MutableLiveData<T>.observeOnce(lifecycleOwner: LifecycleOwner, observer: Observer<T>) {
observe(lifecycleOwner, object : Observer<T> {
override fun onChanged(t: T?) {
observer.onChanged(t)
if (t != null)
removeObserver(this)
}
})
}
So, here we are observing the content and removing observer when we have successful non-null update. You can modify this extension method according to your needs.
But, if you want to do something on null value also then remove if (t != null) and you are good to go.
Your code would like like this and you don’t have to check null value here which is already taken care of in extension function:
val data = MutableLiveData<String>("abc")
data.observeOnce(this, Observer {
print(it)
})
I hope you have found a good workaround.
Happy coding :)