LiveData Observer not Called
To get same reference of ViewModel
of your Activity
you need to pass the same Activity instance, you should use ViewModelProviders.of(getActivity)
. When you pass this
as argument, you receive instance of ViewModel
that associates with your Fragment
.
There are two overloaded methods:
ViewModelProvider.of(Fragment fragment)
ViewModelProvider.of(FragmentActivity activity)
For more info Share data between fragments
I put this code inside the onActivityCreated
fragment, don't underestimate getActivity ;)
if (activity != null) {
globalViewModel = ViewModelProvider(activity!!).get(GlobalViewModel::class.java)
}
globalViewModel.onStop.observe(viewLifecycleOwner, Observer { status ->
Log.d("Parent Viewmodel", status.toString())
})
This code helps me to listening Parent ViewModel changes in fragment.