在同一个活动中创建视图模型的不同实例

问题描述:

最近从Dagger迁移到Hilt之后,我开始观察到关于ViewModels的非常奇怪的行为.下面是代码片段:

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


@HiltAndroidApp
class AndroidApplication : Application() {}

@Singleton
class HomeViewModel @ViewModelInject constructor() :
    ViewModel() {}

@AndroidEntryPoint
class HomeFragment : Fragment(R.layout.fragment_home) {

    private val homeViewModel by viewModels<HomeViewModel>()

    override fun onResume() {
        super.onResume()
        Timber.i("hashCode: ${homeViewModel.hashCode()}")
    }
}


@AndroidEntryPoint
class SomeOtherFragment : Fragment(R.layout.fragment_home) {

    private val homeViewModel by viewModels<HomeViewModel>()

    override fun onResume() {
        super.onResume()
        Timber.i("hashCode: ${homeViewModel.hashCode()}")
    }
}

hashCode的值在所有片段中均不一致.我无法弄清楚我还缺少什么来在活动中生成viewmodel的单例实例.

The value of hashCode isn't consistent in all the fragments. I am unable to figure out what else am I missing for it to generate singleton instance of viewmodel within the activity.

我正在使用单一活动设计,并添加了所有必需的依赖项.

I am using single activity design and have added all the required dependencies.

当您通过viewModels使用 时,您将创建一个范围为该单个Fragment的ViewModel-这意味着每个Fragment都有其自己的单个该ViewModel类的实例.如果您希望将单个ViewModel实例的作用域限定于整个Activity,则需要使用 由activityViewModels

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<HomeViewModel>()