Search code examples
javaandroidkotlinmvvmviewmodel

How to share a ViewModel between custom Views of different Fragments?


I have an Activity which contains 2 Fragments which contains various custom Views each.

How can I share a ViewModel between theses custom Views?

-Fragments-

private val mainViewModel: MainViewModel by activityViewModels()

-Custom Views-

private val mainViewModel by lazy {
    ViewModelProvider(findViewTreeViewModelStoreOwner()!!).get<MainViewModel>()
}

The problem is that findViewTreeViewModelStoreOwner() returns the Fragment instead of the Activity, creating a new ViewModel instead of sharing the existing one.

Is there any way to share an Activity ViewModel between the custom Views?


Solution

  • This happens because findViewTreeViewModelStoreOwner() in your Custom view returns Fragment instead of Activity since your View have attached to Fragment and therefore this method returns Fragment.

    You can try to explicitly cast Activity of your View to ViewModelStoreOwner and get a ViewModel from ViewModelProvider created with this Activity. Then, ViewModel of your Activity has to be returned (Kotlin would do automatic type cast Activity to ViewModelStoreOwner, but just for clarity):

    // Your Activity:
    private val mainViewModel by viewModels<MainViewModel>()
    
    // Your custom views:
    private val mainViewModel by lazy {
        ViewModelProvider(activity as ViewModelStoreOwner).get<MainViewModel>()
    }