[英]Why are Dagger subcomponents declared in a module and not in the parent component directly?
[英]Why is using @Module.subcomponents better than installing a subcomponent via a method on the parent component?
從文檔 :
使用
@Module.subcomponents
更好,因為它允許Dagger檢測是否曾經請求過子組件。 通過方法在父組件上安裝子組件是對該組件的顯式請求,即使從未調用該方法也是如此。 Dagger無法檢測到它,因此即使您從不使用它也必須生成子組件。
有人知道這到底是什么意思嗎?
Dagger不能告訴您是否曾經調用過任何組件方法:這是一個編譯時框架,它生成組件實現,並且實現您放置在組件接口上的每個方法。
@Component(modules = YourModule.class)
public interface YourComponent {
ClassA a();
ClassB b();
ExplicitSubcomponent createExplicitSubcomponent(Dep1 dep1, Dep2 dep2);
}
@Module(subcomponents = ImplicitSubcomponent.class)
public abstract class YourModule {
@Binds ClassC classC(DefaultClassC classCImpl);
}
在上面的示例中,我們有ClassA,ClassB和ClassC。 可以說,在所有這些中,您實際上只需要ClassA:它們實際上並不相互依賴,並且您實際上沒有使用子組件。
b()
已定義,因此有人可能會在某天打電話要求ClassB。 Dagger無法確定是否有人調用b()
,因此它必須創建和引用ClassB以及ClassB傳遞依賴的所有內容的工廠實現。 這說明了Dagger的哲學,即僅編譯可從組件接口本身訪問的內容。 這也適用於子組件:
當然,如果您要使用Proguard或其他靜態分析器修剪構建,則這些工具可能能夠修剪不必要的類或方法。 但是,此時您正在進行代碼生成子組件的工作,正在進行將其編譯為字節碼的工作,然后Proguard正在進行將其刪除的工作。 如果您在知道自己需要子模塊之前就避免編譯子組件,那么在大型項目中效率會更高。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.