I have an activity which is observing livedata from repository. Now when the activity gets destroyed and then created again, i still get the old value from repository unless i fetch the new one manually.
Why is the mutablelivedata retaining its old value even after the observer activity is destroyed?
you can reduce lifetime of your ViewModel, in this case newly created ViewModel won't persist previous data.
Alternatively, you can manually call inside your activity
override fun onDestroy(){
super.onDestroy()
viewModel.clear()
}
inside viewmodel:
fun clear(){ myLiveData.value = defaultValue /*or null*/ }
or change MutableLiveData with LiveEvent
https://proandroiddev.com/livedata-with-single-events-2395dea972a8
You can use SingleLiveData<T>
observer.
class SingleLiveData<T> : MutableLiveData<T?>() {
override fun observe(owner: LifecycleOwner, observer: Observer<in T?>) {
super.observe(owner, Observer { t ->
if (t != null) {
observer.onChanged(t)
postValue(null)
}
})
}
}
Now an instance of MutableLiveData<T>
you can use SingleLiveData<T>
. It will call only one time.
private val data = SingleLiveData<String>()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.