I'm using navigation bottom with shared ViewModel
with all fragments inside navigation bottom but it throws this exception when recall fragment second time
java.lang.IllegalArgumentException: Cannot add the same observer with different lifecycles
I have tried to make all observers attached to activity not to it's fragment as below
1-Declare viewModel in fragemt
viewModel = activity?.run {
ViewModelProviders.of(this,viewModelFactory).get(SharedViewModel::class.java)
} ?: throw Exception("Invalid Activity")
2-Observer livedata object
viewModel.msg.observe(activity!!, Observer {
Log.i(TAG,it)
})
3- remove observer
override fun onStop() {
super.onStop()
viewModel.msg.removeObservers(activity!!)
}
This code is working fine with me, but I wondering if my code is correct and working probably? thanks in advance
It is a common mistake we do while using live-data in fragment. Using this
/activity
on fragment can be duplicate. You should use viewLifecycleOwner
for livedata observing in fragment.
viewModel.msg.observe(viewLifecycleOwner, Observer {
Log.i(TAG,it)
})
For more information, read this article https://medium.com/@cs.ibrahimyilmaz/viewlifecycleowner-vs-this-a8259800367b
You don't need to remove the observer manually.