Dagger2为注入的服务提供监听器的实例

时间:2017-01-17 07:21:44

标签: java dependency-injection dagger-2

我遇到问题我不知道如何解决..

首先,我有n个注入A类的服务,我提供带有侦听器接口B的A类,用于数据共享

    Interface B {
        void onActionA(String a);
        void onActionB(String b);
    }

    class A {
        private B listener;

        protected @Inject C;

        protected @Inject D;

        private AppComponent component;

        A(B listener) {
            this.listener = listener;
            component = DaggerAppComponent.create();
            component.inject(this);
        }

        void onAAction() {
            listener.onActionA("a case");
        }

        void onBAction() {
            listener.onActionB("b case");
        }
    }

有问题我有时需要为A类调用监听器B,而不是从A类调用,但是从注入的服务C或D调用,我可以以某种方式传递给那些注入的服务监听器B吗?

1 个答案:

答案 0 :(得分:0)

不确定整体设计,但是您可以在创建B期间将AppModule的实例传递到AppComponent,从而使其在依赖关系树中可用。

您的AppModule必须看起来像这样:

@Module
public class AppModule {
    private final B listener;

    public AppModule(B listener) {
        this.listener = listener;
    }

    @Provides
    B provideListener() {
        return listener;
    }

    @Provides
    C provideC(B listener) {
        return new C(listener);
    }

    @Provides
    D provideD(B listener) {
        return new D(listener);
    }
}

然后必须使用AppComponent创建AppModule,如下所示:

public class A {
    @Inject B; // either inject or assign in constructor
    @Inject C;
    @Inject D;

    public A(B listener) {
        AppComponent component = DaggerAppComponent.builder()
            .appModule(new AppModule(listener)) // now mandatory because of the non-default constructor
            .build();
        component.inject(this);
    }
}
相关问题