7

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?

Neelabh Anand
  • 71
  • 1
  • 2

2 Answers2

2

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

Lukas
  • 1,216
  • 12
  • 25
  • 1
    Yes currently i am clearing the viewmodel just like you suggested. But i think the livedata should clear itself when the activity gets destroyed. There should be a proper way to do this maybe. – Neelabh Anand Sep 19 '19 at 17:29
1

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>()
Md Imran Choudhury
  • 9,343
  • 4
  • 62
  • 60