Dagger 2 - 绑定到依赖组件的映射

时间:2017-09-24 19:47:41

标签: android mvvm dagger-2 dagger subcomponent

我想知道是否或如何为父组件的地图做出贡献。

这是我对父组件及其图表的设置:

@Singleton
@Component(modules = AppModule.class)
public interface AppComponent {
    @Component.Builder
    interface Builder {
        @BindsInstance
        Builder application(Application application);

        AppComponent build();
    }

    ViewModelProvider.Factory plusViewModelFactory();
}

@Module
public abstract class AppModule {
    @Multibinds
    abstract Map<Class<? extends ViewModel>, ViewModel> bindViewModels();

    @Binds
    abstract ViewModelProvider.Factory bindViewModelFactory(MyViewModelFactory myViewModelFactory);
}

@Singleton
public class MyViewModelFactory implements ViewModelProvider.Factory {
    private final Map<Class<? extends ViewModel>, Provider<ViewModel>> creators;

    @Inject
    MyViewModelFactory(Map<Class<? extends ViewModel>, Provider<ViewModel>> creators) {
        this.creators = creators;
    }

    @Override
    public <T extends ViewModel> T create(Class<T> modelClass) {
        // ... Irrelevant code
    }
}

第二,我希望每个Activity都有一个取决于Component的{​​{1}}:

AppComponent

public class StartActivity extends Activity { @Module static abstract class StartModule { @Binds @IntoMap @ViewModelKey(StartViewModel.class) abstract ViewModel bindStartViewModel(StartViewModel startViewModel); } @StartScope @Component(dependencies = AppComponent.class, modules = StartModule.class) interface StartComponent { void inject(StartActivity startActivity); } @Inject ViewModelProvider.Factory viewModelFactory; @Override protected void onCreate(Bundle savedInstanceState) { StartComponent component = DaggerStartActivity_StartComponent .builder() .appComponent(((MyApplication) getApplication()).getAppComponent()) .build(); component.inject(this); super.onCreate(savedInstanceState); System.out.println(viewModelFactory.toString()); // ... Irrelevant code } } 的绑定ViewModelProvider.Factory已正确注入此AppComponent但显然为空,因为StartActivity根本不绑定任何AppModule的任何提供商{1}}本身。我想要发生的是,每个ViewModel后来绑定的ViewModel的提供者被放入工厂使用的Activity。要么我没有从正确的角度看这个问题,要么Dagger 2中缺少一个功能。

我可以选择将Map组件声明为子组件,但后来我失去了模块性。

0 个答案:

没有答案