如何使用Dagger 2.11注入ViewModel

时间:2018-09-27 07:23:53

标签: android dagger-2 android-viewmodel

我在活动中创建了 ViewModel

mOrdersViewModel = ViewModelProviders.of(this, viewModelFactory).get(OrdersViewModel.class);

我想按如下方式注入它:

@Inject OrdersViewModel mOrdersViewModel

这是我的ViewModel:

public class OrdersViewModel extends ViewModel {

private OrdersRepository trelloRepository; ();

@Inject
OrdersViewModel(@NonNull OrdersRepository repository) {
    this.repository = repository;
}

ViewModelFactory模块:

@Module
public abstract class ViewModelModule {

@Binds
@IntoMap
@ViewModelKey(OrdersViewModel.class)
abstract ViewModel bindMovieListViewModel(OrdersViewModel ordersViewModel);

@Binds
abstract ViewModelProvider.Factory bindViewModelFactory(ProjectViewModelFactory projectViewModelFactory);

最后,我在MainActivity中获得了Viewmodel,所以:

public class MainActivity extends AppCompatActivity implements HasSupportFragmentInjector, OrderCallback {

@Inject
DispatchingAndroidInjector<Fragment> dispatchingAndroidInjector;

@Inject
public ViewModelProvider.Factory viewModelFactory;

private OrdersViewModel mOrdersViewModel;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    AndroidInjection.inject(this);
    ButterKnife.bind(this);
    mOrdersViewModel = ViewModelProviders.of(this, viewModelFactory)
            .get(OrdersViewModel.class);

1 个答案:

答案 0 :(得分:0)

您是否不需要将视图模型模块作为Component类作为应用程序组件?我不是匕首大师,所以对此我不确定。

@Singleton
@Component(modules = [
    ViewModelModule ::class]
)
interface AppComponent {
    @Component.Builder
    interface Builder {
        @BindsInstance
        fun application(application: MyApplication): Builder

        fun build(): AppComponent
    }

    fun inject(app: MyApplication)
}