简体   繁体   中英

LiveData observer is not being called when changing value

My observer is not being called when I change LiveData value. I have a ViewModel , a custom View and a Fragment . In ViewModel I set the LiveData , in the custom View is where I change the value of this LiveData and in Fragment is where I observe the LiveData .

Using breakpoints, I see that my custom View is working fine and changing the LiveData value correctly but in Fragment , the observer only is called when the Fragment is created.

ViewModel:

class MyViewModel : ViewModel {
  private val _myValue : MutableLiveData<Boolean> by lazy{
     MutableLiveData<Boolean>().apply{
         value = false
         }
     }
  val myValue : LiveData<Boolean> get() = _myValue

  fun setMyValue(checked: Boolean){
    _myValue.postValue(checked)
  }
}

CustomView:

    class MyCustomView @JvmOverloads constructor(ctx:Context,attrs:AttributeSet? = null): ConstraintLayout(ctx,attrs){

       private val viewmodel by lazy{
         ViewModelProvider(ViewTreeViewModelStoreOwner.get(this)!!).get<MyViewModel>()
       }
    
       init{
         setValue()
       }
    
       fun setValue(){
         if(something == true){
           viewmodel.setMyValue(true)
       }else{
          viewmodel.setMyValue(false)}
       }
    }
}

Fragment:

class Fragment :Fragment(){
      private val viewModel : MyViewModel by activityViewModels()
    
      override fun onViewCreated(view:View,savedInstanceState: Bundle?){
    
        super.onViewCreated(view,savedInstanceState)
        setUpObserver()
      }
    
      private fun setUpObserver(){
        viewModel.apply{
          myValue.observerInside{ myvalue->
            if(myValue)
               someFunction()
            else
               anotherFunction()

          } 
       }
     }
 }

Solved, I just changed the ViewModel declaration in Fragment to this and its working fine now:

 private val viewmodel by lazy{
         ViewModelProvider(ViewTreeViewModelStoreOwner.get(binding.root)!!).get<MyViewModel>()
 }

In your Fragment class, where you have

private fun setUpObserver(){
    viewModel.apply{
      myValue.observerInside{ myvalue->
        if(myValue)
           someFunction()
        else
           anotherFunction()

      } 
   }

Do this instead

private fun setUpObserver(){
    viewModel.apply {
      myValue.observer { myvalue ->
        ...
      } 
   }
}

As in, replace myValue.observerInside with myValue.observe .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM