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

3

我遇到了一个问题,不确定如何解决...

首先,我有n个服务注入到A类中,并为A类提供了监听器接口B,以便进行数据共享。

    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");
        }
    }

有时我需要从注入的服务C或D调用我的类A的监听器B,我是否可以以某种方式将监听器B传递给这些注入的服务?

1个回答

0

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

你的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);
    }
}

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

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);
    }
}

谢谢,这正是我所需要的。 - Osvaldas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接