<android.arch.lifecycle.ViewModel>> cannot be provided without an @Provides-annotated method

杀马特。学长 韩版系。学妹 提交于 2020-01-24 09:20:13

问题


I am trying to create a viewmodel module like in this example but I am having this error

error: java.util.Map,javax.inject.Provider> cannot be provided without an @Provides-annotated method.

I followed all the example, here are my codes

ViewModelFactory class

@Singleton
public class ViewModelFactory implements ViewModelProvider.Factory {

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

    @Inject
    ViewModelFactory(Map<Class<? extends ViewModel>, Provider<ViewModel>> creators) {
        mCreators = creators;
    }

    @NonNull
    @Override
    public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
        Provider<? extends ViewModel> creator = mCreators.get(modelClass);
        if (creator == null) {
            for (Map.Entry<Class<? extends ViewModel>, Provider<ViewModel>> entry : mCreators
                    .entrySet()) {
                if (modelClass.isAssignableFrom(entry.getKey())) {
                    creator = entry.getValue();
                    break;
                }
            }
        }
        if (creator == null) {
            throw new IllegalArgumentException("unknown model class " + modelClass);
        }
        try {
            return (T) creator.get();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

ViewModelModule class

@Module
public abstract class ViewModelModule {

    @Binds
    abstract ViewModelProvider.Factory bindViewModelFactory(ViewModelFactory factory);

}

and this is the component

@Singleton
@Component(modules = {AppModule.class, ViewModelModule.class})
public interface MainComponent {


    void inject(Sdk sdk);

    void injectTestActivity(TestActivity testActivity);


}

ps: this implementation in android library not in the application project


回答1:


You need to bind your view models using Dagger multibindings. In other words, bind your view models and annotate them with the @IntoMap multibinding annotation. In the same example you posted, you can find an example of it here. In the example, they created the ViewModelKey annotation in order to specify the key from which Dagger can retrieve your view model from the map (usually the view model's class). Dagger will create the map at compile time, and that's why you get the error - if you don't specify any view model to be part of the map, Dagger can't know which types it should instantiate.



来源:https://stackoverflow.com/questions/54319444/android-arch-lifecycle-viewmodel-cannot-be-provided-without-an-provides-anno

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