2

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

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

@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取决于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.FactoryAppComponent正确地注入到 thisStartActivity中,但显然是空的,因为它本身AppModule并没有绑定任何提供者ViewModel。不过,我希望发生的是,ViewModel每个稍后绑定的 s 的提供者都Activity被放入Map工厂使用的同一个中。要么我没有从正确的角度看待这个问题,要么为此目的在 Dagger 2 中缺少一个功能。

可选地,我可以将我Activity的组件声明为子组件,但随后我失去了模块化。

4

0 回答 0