A better alternative would be to use the new API view.findViewTreeViewModelStoreOwner()
which gives you the viewModelStoreOwner(Fragment if view is attached to the fragment o/w activity)
You can create ViewModelProvider and then get the ViewModel.
Below is an example of code in Kotlin
private val viewModel by lazy(LazyThreadSafetyMode.NONE) {
ViewModelProvider(viewModelStoreOwner).get(ViewModel::class.java)
}
Similarly, there are other similar APIs like view.findViewTreeLifecycleOwner()
and view.findViewTreeSavedStateRegistryOwner()
It is a much cleaner approach as you don't have to typecast your context
into Activity
or Fragment
and will scale to other implementations of ViewModelStoreOwner
as well.
One thing to note here is that view may have a shorter life span compared to Activity/Fragment and so you might have to make a custom view Lifecycle(so that your LiveData subscription gets managed properly) using LifecycleRegistry
based on onAttachedToWindow
and onDetachedFromWindow
callbacks