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()
}
}
}
}
CodePudding user response:
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>()
}
CodePudding user response:
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.
