Dagger multibinding of viewmodels using provides instead of constructor injection

大憨熊 提交于 2019-12-10 12:07:27

问题


All examples on how to combine ViewModel with dagger2 has been to use constructor injection on the ViewModelFactory. Like this:

private final Map<Class<? extends ViewModel>, Provider<ViewModel>> providers;

@Inject
public ViewModelFactory(Map<Class<? extends ViewModel>, Provider<ViewModel>> providers) {
    this.providers = providers;
}

While the module could look something like this.

@Module
abstract class ViewModelModule {

    @SuppressWarnings("unused")
    @Binds
    @IntoMap
    @ViewModelKey(value = SomeViewModel.class)
    abstract ViewModel bindSomeViewModel(SomeViewModel viewModel);

    @SuppressWarnings("unused")
    @Binds
    abstract ViewModelProvider.Factory 
    bindViewModelFactory(ViewModelFactory viewModelFactory);
}

Now because I like to write reusable code and so I would like to move the factory into another android library module. So I would like to be able to do something like this:

New constructor (just removed @Inject):

private final Map<Class<? extends ViewModel>, Provider<ViewModel>> providers;

public ViewModelFactory(Map<Class<? extends ViewModel>, Provider<ViewModel>> providers) {
    this.providers = providers;
}

And the module:

@Module
abstract class ViewModelModule {

    @SuppressWarnings("unused")
    @Binds
    @IntoMap
    @ViewModelKey(value = SomeViewModel.class)
    abstract ViewModel bindSomeViewModel(SomeViewModel viewModel);

    @SuppressWarnings("unused")
    @Provides
    ViewModelProvider.Factory 
    provideViewModelFactory(Map<Class<? extends ViewModel>, Provider<ViewModel>> providers) {
        // Manually creates the ViewModelFactory.
        return new ViewModelFactory(providers);
    }
}

This gives me the following error

error: com.example.project.ViewModelModule has errors

Question

How do you inject a ViewModelProvider.Factory residing in another module using @Provides which takes the possible view models it creates in the constructor?

Basically, I wan't to use @Provides and call the constructor explicitly instead of letting Dagger do it with constructor injection using @Binds here.

来源:https://stackoverflow.com/questions/56739361/dagger-multibinding-of-viewmodels-using-provides-instead-of-constructor-injectio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!