簡體   English   中英

Dagger2提供偵聽器實例以注入服務

[英]Dagger2 provide instance of listener to injected service

我遇到問題,我不確定該如何解決。

首先,我向類A注入了n種服務,並且為類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");
        }
    }

有時我需要從類A而是從注入的服務C或D調用類A的偵聽器B,這是一個問題,我可以通過某種方式傳遞給那些注入的服務偵聽器B嗎?

不知道的整體設計,但肯定的,你可以通過實例BAppModule創作的過程中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);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM