简体   繁体   English

使用 Hilt 将 ViewModel 注入 ViewModel

[英]Injecting ViewModel into ViewModel with Hilt

I'm currently working on a big project where I have a ViewModelA using MediatorLiveData to observe other LiveData sources.我目前正在做一个大项目,我有一个 ViewModelA 使用 MediatorLiveData 来观察其他 LiveData 源。 I would like to have this ViewModelA observing data from a ViewModelB.我想让这个 ViewModelA 观察来自 ViewModelB 的数据。

One way to solve this would be having the Fragment using both view models and updating ViewModelA when ViewModelB data changes.解决此问题的一种方法是让 Fragment 同时使用视图模型并在 ViewModelB 数据更改时更新 ViewModelA。

@AndroidEntryPoint
class FragmentA: Fragment() {

    //ViewModels
    private val viewModelA: ViewModelA by viewModels()
    private val viewModelB: ViewModelB by viewModels()

    onViewCreated... {
       viewModelA.someFunction().observe{
           viewModelB.someLiveData.value = it
       }
    }
}

However I came up with another solution where I inject ViewModelB into ViewModelA's constructor using Hilt.但是我想出了另一个解决方案,我使用 Hilt 将 ViewModelB 注入 ViewModelA 的构造函数。

class ViewModelA @ViewModelInject constructor(
        private val viewModelB: ViewModelB
) : ViewModel() {}

It currently works but I don't think this would be a good practice.它目前有效,但我认为这不是一个好习惯。 I couldn't find much info online on this matter.我在网上找不到太多关于这个问题的信息。 Would that cause any problems?这会引起任何问题吗?

You can achieve the same if you forward the result from ViewModelA to ViewModelB .如果将结果从ViewModelA转发到ViewModelB ,则可以实现相同的效果。 This will give you the benefit of separation, viewmodels wont be intertwined and improved testability.这将为您带来分离的好处,视图模型不会交织在一起并提高可测试性。 ViewModelA should not be aware who is consuming the result. ViewModelA不应该知道谁在使用结果。

viewModela.myLiveData.observe(viewLifecycleOwner, viewModelB::onDataRetrieved)

In onDataRetrieved you will have your own logic for calling viewModelB.someLiveDataonDataRetrieved ,您将拥有自己的调用viewModelB.someLiveData的逻辑

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM