小编Mr *_*ike的帖子

匕首 - 我们应该为每个活动/片段创建每个组件和模块

我已经和dagger2合作了一段时间.我为每个Activity/Fragment创建一个自己的组件/模块感到困惑.请帮我澄清一下:

例如,我们有一个应用程序,该应用程序有大约50个屏幕.我们将实现遵循MVP模式的代码和用于DI的Dagger2.假设我们有50个活动和50个演示者.

在我看来,通常我们应该像这样组织代码:

  1. 创建一个AppComponent和AppModule,它将提供应用程序打开时将使用的所有对象.

    @Module
    public class AppModule {
    
        private final MyApplicationClass application;
    
        public AppModule(MyApplicationClass application) {
            this.application = application;
        }
    
        @Provides
        @Singleton
        Context provideApplicationContext() {
            return this.application;
        }
    
        //... and many other providers 
    
    }
    
    @Singleton
    @Component( modules = { AppModule.class } )
    public interface AppComponent {
    
        Context getAppContext();
    
        Activity1Component plus(Activity1Module module);
        Activity2Component plus(Activity2Module module);
    
        //... plus 48 methods for 48 other activities. Suppose that we don't have any other Scope (like UserScope after user login, ....)
    
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 创建ActivityScope:

    @Scope …
    Run Code Online (Sandbox Code Playgroud)

android dagger dagger-2

79
推荐指数
3
解决办法
2万
查看次数

标签 统计

android ×1

dagger ×1

dagger-2 ×1