Hilt creating different instances of view model inside same activity

前端 未结 2 1539
伪装坚强ぢ
伪装坚强ぢ 2021-01-06 12:44

After recently migrating from Dagger to Hilt I started observing very strange behavior with respect to ViewModels. Below is the code snippet:


@HiltAndroidApp         


        
2条回答
  •  既然无缘
    2021-01-06 13:36

    When you use by viewModels, you are creating a ViewModel scoped to that individual Fragment - this means each Fragment will have its own individual instance of that ViewModel class. If you want a single ViewModel instance scoped to the entire Activity, you'd want to use by activityViewModels

    private val homeViewModel by activityViewModels()
    

提交回复
热议问题