androidkotlinandroid-viewmodeldaggerdagger-hilt

How to use Shared ViewModel in fragment


I want to make a ViewModel shared between multiple fragments we try it before hilt and it works fine but after hilt ViewModel is created twice

my question is how to get the same ViewModel each time with the hilt

@HiltViewModel

Solution

  • For shared VM you use viewModel by activityViewModels<MyViewModel>() in fragment . Never create a Singleton ViewModel this kind of defeat the purpose of having ViewModel .

    This extension comes from fragment ktx library . you can add it with following dependency. Change the version to the latest one from AndroidX release notes

     def activity_version = "1.2.0"
     def fragment_version = "1.3.0"
     implementation "androidx.activity:activity-ktx:$activity_version"
     implementation "androidx.fragment:fragment-ktx:$fragment_version"
    

    When you inject it you can use the it as :

     @AndroidEntryPoint
    class MyFragment : Fragment(){
        private val viewModel by activityViewModels<MyViewModel>()
    }