本文介绍了如何使用匕首注入SharedViewModel?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在Activity中创建了SharedViewModel
I create my SharedViewModel in Activity :
mOrdersViewModel=ViewModelProviders.of(this,viewModelFactory.get(OrdersViewModel.class);
之后,我在其他组件(片段)中订阅了LiveData
After, I subscribe to the LiveData in the other components(Fragments)
mOrdersViewModel = ViewModelProviders.of(Objects.requireNonNull(getActivity())).get(OrdersViewModel.class);
但是我想使用 mOrdersViewModel
,所以 @Inject OrdersViewModel;
如何注入我的mOrdersViewModel.请帮助我(.
How can I inject my mOrdersViewModel. Help me please (.
推荐答案
在您的 Component
处,像这样注入您的活动:
At your Component
, inject your activity like this :
void inject(Activity activity);
然后在您的 模块
中为您的 ViewModel
提供类似的依赖关系:
And in your Module
provide dependency like this for your ViewModel
:
public Module(Activity activity) {
this.mActivity = activity;
}
@Provides
YourViewModel provideViewModel(YourViewModel viewModel){
return ViewModelProviders.of(mActivity).get(viewModel.getClass());
}
在这样的活动中,
@Inject
YourViewModel mViewModel;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
Component mActivityComponent = DaggerActivityComponent.builder()
.activityModule(new Module(this))
.build();
// then
mActivityComponent.inject(this);
// Now you can use your viewModel object in activity anywhere.
}
这篇关于如何使用匕首注入SharedViewModel?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!