3

I have a question about MutableLiveData in Viewmodel. Does just setValue function of MutableLiveData trigger observation? If we change content of MutableLiveData witout setValue, may it be triggered?

Tom11
  • 2,419
  • 8
  • 30
  • 56
ahmetvefa53
  • 581
  • 6
  • 20

3 Answers3

1

I doubt it. Only the mothods below dispatch events to observables:

liveData.postValue("a");
liveData.setValue("b");

https://developer.android.com/reference/android/arch/lifecycle/MutableLiveData

Jeremi
  • 1,314
  • 3
  • 16
  • 40
1

It will only trigger if you call setValue or postValue. If you use Kotlin then you can write yourself an extension to trigger the LiveData:

fun <T> MutableLiveData<T>.trigger() {
    value = value
}

and then you can simply call:

mutableLiveData.trigger()
Paul Spiesberger
  • 5,630
  • 1
  • 43
  • 53
0

Both setValue() & postValue will trigger the events. The only difference is, postValue() can trigger the observation event from background thread as well. Whereas, setValue must be called within main thread. postValue() is preferred to setValue().

Tom11
  • 2,419
  • 8
  • 30
  • 56
Ningan
  • 151
  • 1
  • 8