Search code examples
androidmvvmviewmodel

How to use same instance of ViewModel in activity as well as fragment?


I have created an instance of ViewModel in MainActivity and setup an observer. I want the observed data into one of the fragments of MainActivity's ViewPager. How can I get the required LiveData into the fragment.


Solution

  • Using AndroidX extension delegate

    In the MainActivity:

    private val activityViewModel: SomeViewModel by viewModels()
    

    In the Fragement

    private val activityViewModel: SomeViewModel by activityViewModels()
    

    With ViewModelFactory, put the ViewModelFactory intance into closure

    private val activityViewModel: SomeViewModel by viewModels{ viewModelFactory }
    private val activityViewModel: SomeViewModel by activityViewModels{ viewModelFactory}