Home > Software design >  MutableLivedata observer triggers only value is changed
MutableLivedata observer triggers only value is changed

Time:06-21

class MainViewModel :ViewModel(){
    private val _text = MutableLiveData<String>()
    val text get() = _text.distinctUntilChanged()

    fun setToA(){ 
      _text.value = "A"
    } 
    fun setToB(){ 
      _text.value = "B"
    } 
}

I'm observing text in Fragment like this.

//in Fragment
    btnA.setOnClickListener {
        mainviewmodel.setToA()
    }

    btnB.setOnClickListener {
        mainviewmodel.setToB()
    }
    
    mainviewmodel.text.observe(viewLifecycleOwner){
            //TODO
    }

I sometimes click btnA 2 times in a row. Whenever I setValue with same value (such as A) in a row,

observer doesn't trigger. observer triggers when only text is changed. ( whenever A -> B or B -> A)

I want to let observer triggers when I setValue text with same value in a row. How can I do it??

CodePudding user response:

This is happening because you are using distinctUntilChanged(). Try like below.

val text : LiveData<String>
   get() = _text 
  • Related