简体   繁体   English

更改值时未调用 LiveData 观察者

[英]LiveData observer is not being called when changing value

My observer is not being called when I change LiveData value.当我更改LiveData值时,不会调用我的观察者。 I have a ViewModel , a custom View and a Fragment .我有一个ViewModel ,一个自定义View和一个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 .ViewModel中我设置LiveData ,在自定义View中我更改此LiveData的值,在Fragment中我观察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.使用断点,我看到我的自定义View工作正常并正确更改LiveData值,但在Fragment中,仅在创建Fragment时调用观察者。

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:解决了,我刚刚将Fragment中的ViewModel声明更改为这个,现在它工作正常:

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

In your Fragment class, where you have在你的 Fragment 类中,你有

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 .如中所示,将myValue.observerInside替换为myValue.observe

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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