I have a ViewModel handling my business logic and I am using Koin to inject this into my activity and each of my fragments. However after I navigate from Fragment A - Fragment B and navigate back to Fragment A, my observer is triggered again. Why is this happening and how do I stop this onChanged being triggered when I navigate back?
I have tried setting both 'this' and 'viewLifecycleOwner' as the LifecycleOwner of the LiveData.
I have also tried moving the observable to onCreate, onActivityCreated and onViewCreated
My ViewModel:
class MyViewModel : ViewModel() {
private val _myData = MutableLiveData<Data>()
val myData = LiveData<Data>()
get() = _myData
fun doSomething() {
... // some code
_myData.postValue(myResult)
}
MyActivity:
class Activity : BaseActivity() {
private val viewModel by viewModel<MyViewModel>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
setSupportActionBar(main_toolbar)
subscribeUI()
}
private fun subscribeUI() {
myViewModel.isLoading.observe(this, Observer {
toggleProgress(it)
})
}
}
Fragment A:
class FragmentA : BaseFragment() {
private val viewModel by sharedViewModel<MyViewModel>()
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
subscribeUI()
}
private fun subscribeUI() {
viewModel.myData.observe(viewLifecycleOwner, Observer {
val direction =
FragmentADirections.actionAtoB()
mainNavController?.navigate(direction)
})
}
}
Fragment B:
class FragmentB : BaseFragment() {
private val authViewModel by sharedViewModel<LoginViewModel>()
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
subscribeUI()
}
private fun subscribeUI() {
viewModel.otherData.observe(viewLifecycleOwner, Observer {
// Do something else...
})
}
}
When I navigate from Fragment A -> Fragment B, everything works as I expect. However when I navigate back to Fragment A from Fragment B (by pressing the back button) the onChanged method from the Observer on myData is called and the navigation moves back to Navigation B.