Dagger2 Activity子作用域多绑定

参考文章:http://frogermcs.github.io/activities-multibinding-in-dagger-2/
在上一篇文章中,我对Dagger生成的源码进行了分析,顺便自定义了一下作用域,分析了作用域的实现原理。但是对于上一篇中自定义作用域这一块儿,还是有些不妥的。原因有二:
1.Activity依赖于AppComponent,如果我们想要拿到Subcomponent,就必须得先拿到AppComponent对象,还是挺心烦的。
2.AppComponent必须得为所有的Subcomponent定义Factory: MainActivityComponent plus(MainActivityComponent.ModuleImpl module);

描述完了问题就来看看解决方案。从Dagger2.7开始,声明Subcomponent的父作用域有了新的方案。

首先,为所有的ActivityComponent的builder定义一个基本接口:

public interface ActivityComponentBuilder<M extends ActivityModule, C extends ActivityComponent> {
    ActivityComponentBuilder<M, C> activityModule(M activityModule);
    C build();
}

SubComponent可以是下面这样:

@ActivityScope
@Subcomponent(
        modules = MainActivityComponent.MainActivityModule.class
)
public interface MainActivityComponent extends ActivityComponent<MainActivity> {

    @Subcomponent.Builder
    interface Builder extends ActivityComponentBuilder<MainActivityModule, MainActivityComponent> {
    }

    @Module
    class MainActivityModule extends ActivityModule<MainActivity> {
        MainActivityModule(MainActivity activity) {
            super(activity);
        }
    }
}

现在,我们希望有一个SubComponents的builders的集合,这样我们在每个Activity中都可以获取到需要的builder。可以用Multibinding的特性。

@Module(
        subcomponents = {
                MainActivityComponent.class,
                SecondActivityComponent.class
        })
public abstract class ActivityBindingModule {

    @Binds
    @IntoMap
    @ActivityKey(MainActivity.class)
    public abstract ActivityComponentBuilder mainActivityComponentBuilder(MainActivityComponent.Builder impl);

    @Binds
    @IntoMap
    @ActivityKey(SecondActivity.class)
    public abstract ActivityComponentBuilder secondActivityComponentBuilder(SecondActivityComponent.Builder impl);
}

ActivityBindingModule在AppComponent中创建。因为这样,MainActivityComponent和SecondActivityComponent才能是AppComponent的SubComponents.
现在咱们可以注入SubComponent的builders的Map集合了:

public class MyApplication extends Application implements HasActivitySubcomponentBuilders {

    @Inject
    Map<Class<? extends Activity>, ActivityComponentBuilder> activityComponentBuilders;

    private AppComponent appComponent;

    public static HasActivitySubcomponentBuilders get(Context context) {
        return ((HasActivitySubcomponentBuilders) context.getApplicationContext());
    }

    @Override
    public void onCreate() {
        super.onCreate();
        appComponent = DaggerAppComponent.create();
        appComponent.inject(this);
    }

    @Override
    public ActivityComponentBuilder getActivityComponentBuilder(Class<? extends Activity> activityClass) {
        return activityComponentBuilders.get(activityClass);
    }
}

由于builders的Map集合没必要一定要注入到Application中,所以咱们有一个额外的抽象,HasActivitySubcomponentBuilders.

public interface HasActivitySubcomponentBuilders {
    ActivityComponentBuilder getActivityComponentBuilder(Class<? extends Activity> activityClass);
}

最后,Activity真正的实现就可以是下面这样:

public class MainActivity extends BaseActivity {

    //...

    @Override
    protected void injectMembers(HasActivitySubcomponentBuilders hasActivitySubcomponentBuilders) {
        ((MainActivityComponent.Builder) hasActivitySubcomponentBuilders.getActivityComponentBuilder(MainActivity.class))
                .activityModule(new MainActivityComponent.MainActivityModule(this))
                .build().injectMembers(this);
    }
}

上面就是所需的所有代码。现在来看看实现原理,走一遍流程会对整个过程更加清晰。
DaggerAppComponent:

public final class DaggerAppComponent implements AppComponent {
  private Provider<MainActivityComponent.Builder> mainActivityComponentBuilderProvider;

  private Provider<ActivityComponentBuilder> mainActivityComponentBuilderProvider2;

  private Provider<SecondActivityComponent.Builder> secondActivityComponentBuilderProvider;

  private Provider<ActivityComponentBuilder> secondActivityComponentBuilderProvider2;

  private Provider<Map<Class<? extends Activity>, Provider<ActivityComponentBuilder>>>
      mapOfClassOfAndProviderOfActivityComponentBuilderProvider;

  private MembersInjector<MyApplication> myApplicationMembersInjector;

  private Provider<Utils> provideUtilsProvider;

  private DaggerAppComponent(Builder builder) {
    assert builder != null;
    initialize(builder);
  }

  public static Builder builder() {
    return new Builder();
  }

  public static AppComponent create() {
    return builder().build();
  }

  @SuppressWarnings("unchecked")
  private void initialize(final Builder builder) {

    this.mainActivityComponentBuilderProvider =
        new Factory<MainActivityComponent.Builder>() {
          @Override
          public MainActivityComponent.Builder get() {
            return new MainActivityComponentBuilder();
          }
        };

    this.mainActivityComponentBuilderProvider2 = (Provider) mainActivityComponentBuilderProvider;

    this.secondActivityComponentBuilderProvider =
        new Factory<SecondActivityComponent.Builder>() {
          @Override
          public SecondActivityComponent.Builder get() {
            return new SecondActivityComponentBuilder();
          }
        };

    this.secondActivityComponentBuilderProvider2 =
        (Provider) secondActivityComponentBuilderProvider;

    this.mapOfClassOfAndProviderOfActivityComponentBuilderProvider =
        MapProviderFactory.<Class<? extends Activity>, ActivityComponentBuilder>builder(2)
            .put(MainActivity.class, mainActivityComponentBuilderProvider2)
            .put(SecondActivity.class, secondActivityComponentBuilderProvider2)
            .build();

    this.myApplicationMembersInjector =
        MyApplication_MembersInjector.create(
            mapOfClassOfAndProviderOfActivityComponentBuilderProvider);

    this.provideUtilsProvider =
        DoubleCheck.provider(AppModule_ProvideUtilsFactory.create(builder.appModule));
  }

  @Override
  public MyApplication inject(MyApplication application) {
    myApplicationMembersInjector.injectMembers(application);
    return application;
  }

  public static final class Builder {
    private AppModule appModule;

    private Builder() {}

    public AppComponent build() {
      if (appModule == null) {
        this.appModule = new AppModule();
      }
      return new DaggerAppComponent(this);
    }

    public Builder appModule(AppModule appModule) {
      this.appModule = Preconditions.checkNotNull(appModule);
      return this;
    }
  }

  private final class MainActivityComponentBuilder implements MainActivityComponent.Builder {
    private MainActivityComponent.MainActivityModule mainActivityModule;

    @Override
    public MainActivityComponent build() {
      if (mainActivityModule == null) {
        throw new IllegalStateException(
            MainActivityComponent.MainActivityModule.class.getCanonicalName() + " must be set");
      }
      return new MainActivityComponentImpl(this);
    }

    @Override
    public MainActivityComponentBuilder activityModule(
        MainActivityComponent.MainActivityModule activityModule) {
      this.mainActivityModule = Preconditions.checkNotNull(activityModule);
      return this;
    }
  }

  private final class MainActivityComponentImpl implements MainActivityComponent {
    private Provider<MainActivity> provideActivityProvider;

    private Provider<MainActivityPresenter> mainActivityPresenterProvider;

    private MembersInjector<MainActivity> mainActivityMembersInjector;

    private MainActivityComponentImpl(MainActivityComponentBuilder builder) {
      assert builder != null;
      initialize(builder);
    }

    @SuppressWarnings("unchecked")
    private void initialize(final MainActivityComponentBuilder builder) {

      this.provideActivityProvider =
          DoubleCheck.provider(
              ActivityModule_ProvideActivityFactory.create(builder.mainActivityModule));

      this.mainActivityPresenterProvider =
          DoubleCheck.provider(
              MainActivityPresenter_Factory.create(
                  provideActivityProvider, DaggerAppComponent.this.provideUtilsProvider));

      this.mainActivityMembersInjector =
          MainActivity_MembersInjector.create(mainActivityPresenterProvider);
    }

    @Override
    public void injectMembers(MainActivity arg0) {
      mainActivityMembersInjector.injectMembers(arg0);
    }
  }

  private final class SecondActivityComponentBuilder implements SecondActivityComponent.Builder {
    private SecondActivityComponent.SecondActivityModule secondActivityModule;

    @Override
    public SecondActivityComponent build() {
      if (secondActivityModule == null) {
        throw new IllegalStateException(
            SecondActivityComponent.SecondActivityModule.class.getCanonicalName() + " must be set");
      }
      return new SecondActivityComponentImpl(this);
    }

    @Override
    public SecondActivityComponentBuilder activityModule(
        SecondActivityComponent.SecondActivityModule activityModule) {
      this.secondActivityModule = Preconditions.checkNotNull(activityModule);
      return this;
    }
  }

  private final class SecondActivityComponentImpl implements SecondActivityComponent {
    private Provider<SecondActivity> provideActivityProvider;

    private Provider<SecondActivityPresenter> secondActivityPresenterProvider;

    private MembersInjector<SecondActivity> secondActivityMembersInjector;

    private SecondActivityComponentImpl(SecondActivityComponentBuilder builder) {
      assert builder != null;
      initialize(builder);
    }

    @SuppressWarnings("unchecked")
    private void initialize(final SecondActivityComponentBuilder builder) {

      this.provideActivityProvider =
          DoubleCheck.provider(
              ActivityModule_ProvideActivityFactory.create(builder.secondActivityModule));

      this.secondActivityPresenterProvider =
          DoubleCheck.provider(SecondActivityPresenter_Factory.create(provideActivityProvider));

      this.secondActivityMembersInjector =
          SecondActivity_MembersInjector.create(secondActivityPresenterProvider);
    }

    @Override
    public void injectMembers(SecondActivity arg0) {
      secondActivityMembersInjector.injectMembers(arg0);
    }
  }
}

咱们所需的代码大部分都在这个类了。
老规矩,先来看看是怎么调用注入的。

@Override
    protected void injectMembers(HasActivitySubcomponentBuilders hasActivitySubcomponentBuilders) {
        ((MainActivityComponent.Builder) hasActivitySubcomponentBuilders.getActivityComponentBuilder(MainActivity.class))
                .activityModule(new MainActivityComponent.MainActivityModule(this))
                .build()
                .injectMembers(this);
    }

此方法在BaseActivity中调用,传入的hasActivitySubcomponentBuilders其实是Application(Application实现了HasActivitySubcomponentBuilders接口)。调用Application的getActivityComponentBuilder方法,再把返回值强转成MainActivityBuilder类型。来看看Application类:

public class MyApplication extends Application implements HasActivitySubcomponentBuilders {

    @Inject
    Map<Class<? extends Activity>, Provider<ActivityComponentBuilder>> activityComponentBuilders;

    private AppComponent appComponent;

    public static HasActivitySubcomponentBuilders get(Context context) {
        return ((HasActivitySubcomponentBuilders) context.getApplicationContext());
    }

    @Override
    public void onCreate() {
        super.onCreate();
        appComponent = DaggerAppComponent.create();
        appComponent.inject(this);
    }

    @Override
    public ActivityComponentBuilder getActivityComponentBuilder(Class<? extends Activity> activityClass) {
        return activityComponentBuilders.get(activityClass).get();
    }
}

OK,Application的get方法返回一个ActivityComponentBuilder实例,是从activityComponentBuilders集合中取出来的。嘿?这个集合哪来的?往上看就发现,这个集合是通过依赖注入注入进来的。
咱们回到DaggerAppComponent中看一眼,在initialize初始化方法中发现这么一句:

this.mapOfClassOfAndProviderOfActivityComponentBuilderProvider =
        MapProviderFactory.<Class<? extends Activity>, ActivityComponentBuilder>builder(2)
            .put(MainActivity.class, mainActivityComponentBuilderProvider2)
            .put(SecondActivity.class, secondActivityComponentBuilderProvider2)
            .build();

变量名够直白了吧,这是一个ActivityComponentBuilder和Activity class的映射表。把MainActivity和SecondActivity以及他们相应的Provider放到了集合当中。这句后面就是:

this.myApplicationMembersInjector =
        MyApplication_MembersInjector.create(
            mapOfClassOfAndProviderOfActivityComponentBuilderProvider);

创建了Injector,把Map传给他。在Injector里面就走注入那套流程。
好,回到调用上来:

((MainActivityComponent.Builder) hasActivitySubcomponentBuilders.getActivityComponentBuilder(MainActivity.class))
                .activityModule(new MainActivityComponent.MainActivityModule(this))
                .build()
                .injectMembers(this);

现在我们知道,传一个MainActivity到getActivityComponentBuilder中,会从映射表中拿到MainActivity对应的ComponentBuilder返给我们。然后我们将它强转为MainActivityComponent.Builder. 这个Builder也是一个接口,并且继承自ActivityComponentBuilder:

@Subcomponent.Builder
    interface Builder extends ActivityComponentBuilder<MainActivityModule, MainActivityComponent> {
    }

MainActivityComponent的Module也是一个内部类,也定义在MainActivityComponent中。MainActivityComponentBuilder真正的实现也在DaggerAppComponent中。

private final class MainActivityComponentBuilder implements MainActivityComponent.Builder {
    private MainActivityComponent.MainActivityModule mainActivityModule;

    @Override
    public MainActivityComponent build() {
      if (mainActivityModule == null) {
        throw new IllegalStateException(
            MainActivityComponent.MainActivityModule.class.getCanonicalName() + " must be set");
      }
      return new MainActivityComponentImpl(this);
    }

    @Override
    public MainActivityComponentBuilder activityModule(
        MainActivityComponent.MainActivityModule activityModule) {
      this.mainActivityModule = Preconditions.checkNotNull(activityModule);
      return this;
    }
  }

可以看到,咱们拿到了MainActivityComponent.Builder实例后,new一个MainActivityComponent.Module传进去,然后调用build,build方法会创建一个MainActivityComponentImpl实例并返回:

private final class MainActivityComponentImpl implements MainActivityComponent {
    private Provider<MainActivity> provideActivityProvider;

    private Provider<MainActivityPresenter> mainActivityPresenterProvider;

    private MembersInjector<MainActivity> mainActivityMembersInjector;

    private MainActivityComponentImpl(MainActivityComponentBuilder builder) {
      assert builder != null;
      initialize(builder);
    }

    @SuppressWarnings("unchecked")
    private void initialize(final MainActivityComponentBuilder builder) {

      this.provideActivityProvider =
          DoubleCheck.provider(
              ActivityModule_ProvideActivityFactory.create(builder.mainActivityModule));

      this.mainActivityPresenterProvider =
          DoubleCheck.provider(
              MainActivityPresenter_Factory.create(
                  provideActivityProvider, DaggerAppComponent.this.provideUtilsProvider));

      this.mainActivityMembersInjector =
          MainActivity_MembersInjector.create(mainActivityPresenterProvider);
    }

    @Override
    public void injectMembers(MainActivity arg0) {
      mainActivityMembersInjector.injectMembers(arg0);
    }
  }

最后,我们调用的是MainActivityComponentImpl的injectMembers的方法执行注入。

以上就是解决开篇提到的两个问题的方案:
1.Activity依赖于AppComponent,如果我们想要拿到Subcomponent,就必须得先拿到AppComponent对象,还是挺心烦的。
2.AppComponent必须得为所有的Subcomponent定义Factory: MainActivityComponent plus(MainActivityComponent.ModuleImpl module);
老外管这个叫做Activities Subcomponents Multibinding, Activity子作用域多绑定...成功将子作用域和父作用域解耦。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 205,236评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,867评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,715评论 0 340
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,899评论 1 278
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,895评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,733评论 1 283
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,085评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,722评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,025评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,696评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,816评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,447评论 4 322
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,057评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,009评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,254评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,204评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,561评论 2 343

推荐阅读更多精彩内容