Dagger2 | 五、扩展 - @Scope

本章讨论范围注解(@Scope),它声明依赖的作用域。换句话说,范围注解是为了定义实例的生命周期,在此生命周期内,实例属于单例模式,一旦离开生命周期,实例将被回收,内存空间得到释放。

查看 @Scope 注解的 API 描述:

Identifies scope annotations. A scope annotation applies to a class containing an injectable constructor and governs how the injector reuses instances of the type. By default, if no scope annotation is present, the injector creates an instance (by injecting the type's constructor), uses the instance for one injection, and then forgets it. If a scope annotation is present, the injector may retain the instance for possible reuse in a later injection. If multiple threads can access a scoped instance, its implementation should be thread safe. The implementation of the scope itself is left up to the injector.

这里吐槽一下,JDK 相关的 API 就像哲学一样高深莫测。

简单理解就是:@Scope 注解标记在自定义注解上,指导注入器如何重用实例。

前面讨论的 @Singleton 就是用 @Scope 标记的注解,可以用来生成全局单例依赖。

5.1 @Scope

模仿 @Singleton 注解创建 @ActivityScoped 注解:

@Scope
@Documented // 这个注解实际上可以不用加,只是模仿需要
@Retention(RetentionPolicy.RUNTIME)
public @interface ActivityScoped {
}

替换 ActivityComponent 中的 @Singleton 注解:

@ActivityScoped
@Component(modules = {AccountModule.class})
public interface ActivityComponent {
// ...
}

同时替换 AccountModule 中的 @Singleton 注解:

@Module
final class AccountModule {

    @ActivityScoped
    @Provides
    Account provideAccount() {
        return new Account();
    }

    @ActivityScoped
    @Provides
    PasswordEncoder providePasswordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

    @ActivityScoped
    @Provides
    Gson provideGson() {
        return new Gson();
    }
}

编译生成代码:

public final class DaggerActivityComponent implements ActivityComponent {
  // ...

  private DaggerActivityComponent(AccountModule accountModuleParam) {

    initialize(accountModuleParam);
  }

  // ...

  @SuppressWarnings("unchecked")
  private void initialize(final AccountModule accountModuleParam) {
    this.provideAccountProvider = DoubleCheck.provider(AccountModule_ProvideAccountFactory.create(accountModuleParam));
    this.providePasswordEncoderProvider = DoubleCheck.provider(AccountModule_ProvidePasswordEncoderFactory.create(accountModuleParam));
    this.provideGsonProvider = DoubleCheck.provider(AccountModule_ProvideGsonFactory.create(accountModuleParam));
  }

  // ...
}

不难发现,自定义的 @ActivityScoped 注解和 @Singleton 注解一样,都实现为单例模式。

注意,所有依赖都在 @Component 实例中持有,一旦创建多个 @Component 实例,依赖也会多次初始化,则单例模式被破坏。这恰好说明 @Scope 是将依赖限制在 @Component 中缓存。

5.2 破坏单例

创建 AccountActivity 类:

public class AccountActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account);

        // 第一次创建组件
        Account firstAccount = DaggerActivityComponent.create().account();
        ((TextView) findViewById(R.id.first_account)).setText(firstAccount.toString());
        // 第二次创建组件
        Account secondAccount = DaggerActivityComponent.create().account();
        ((TextView) findViewById(R.id.second_account)).setText(secondAccount.toString());

        Log.e("Account", "first equals second: " + firstAccount.equals(secondAccount));
    }
}

创建 activity_account.xml 布局:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".AccountActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <TextView
            android:id="@+id/first_account"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <Space
            android:layout_width="match_parent"
            android:layout_height="8dp" />

        <TextView
            android:id="@+id/second_account"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

注册 AccountActivity 类到 AndroidManifest.xml 文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.github.mrzhqiang.dagger2_example">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".AccountActivity" />

    </application>
</manifest>

修改 MainActivity 类,在 onCreate() 方法末尾添加内容:

startActivity(new Intent(this, AccountActivity.class));

现在运行看看:

多组件实例运行截图
多组件实例运行日志

正如我们所推测的那样,从组件的不同实例中,获取的 Account 实例也不一样。

因此,只有保证组件实例全局唯一,@Singleton 标记的类才算是真正的单例。

5.3 自定义应用

在 Android 中,全局唯一的是 Application 实例(单进程应用),我们可以创建自定义应用,并让它持有 ActivityComponent 实例,从而在整个应用的生命周期中保证 @Singleton 注解的单例性质。

创建 DaggerApplication 应用:

public class DaggerApplication extends Application {

    private ActivityComponent component;

    @Override
    public void onCreate() {
        super.onCreate();

        component = DaggerActivityComponent.create();
    }

    public static ActivityComponent ofComponent(Context context) {
        return ((DaggerApplication) context.getApplicationContext()).component;
    }
}

只有通过 Context 才能拿到 ActivityComponent 实例去注入 Activity 级别的依赖。

注意,自定义 Application 需要注册到 AndroidManifest 文件:

    <application
        android:name=".DaggerApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
    <!-- 省略其他代码 -->
    </application>

5.3.1 重构页面

MainActivity 类和 AccountActivity 类迁移到新建的 ui 包中:

重构页面之后的结构

在开发中,类似的重构优化很常见,这可以帮助我们更好的理解架构设计。

5.3.2 消除多组件

之前创建多个 ActivityComponent 实例,现在需要消除它们,并改为通过 DaggerApplication 类获取。

修改 MainActivity 类:

public class MainActivity extends AppCompatActivity {
    // ...

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ActivityComponent component = DaggerApplication.ofComponent(this);
        component.inject(this);

        // ...
    }
}

修改 AccountActivity 类:

public class AccountActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account);

        Account firstAccount = DaggerApplication.ofComponent(this).account();
        ((TextView) findViewById(R.id.first_account)).setText(firstAccount.toString());
        Account secondAccount = DaggerApplication.ofComponent(this).account();
        ((TextView) findViewById(R.id.second_account)).setText(secondAccount.toString());

        Log.i("Account", "first equals second: " + firstAccount.equals(secondAccount));
    }
}

现在运行应用,看看单例是否恢复正常。

  • MainActivity 运行截图:
MainActivity 运行截图
  • AccountActivity 运行截图:
AccountActivity 运行截图

显示的 toString() 内容完全一样,说明单例恢复正常。

5.4 范围论述

针对 @Scope 需要明确一些概念,以便在设计 子组件多模块 时,不会产生较大的困扰。

5.4.1 应用范围

顾名思义,@Singleton 注解是单例,标记整个应用范围内唯一的实例。

由此引发出一个问题,哪些属于应用范围呢?

  1. 昂贵的创建成本:如申请网络访问、创建数据库连接池之类

  2. 使用频率非常高:如序列化、编解码之类

这两种实例跟随应用的整个生命周期,同舟共济。

如图所示:

Dagger2-Application-@Scope.png

注意,应用范围的实例常驻内存,除非退出应用,否则实例不会被回收,因此特别要防止内存泄漏。

5.4.2 页面范围

在 Android 的四大组件中,只有 Activity 页面经常创建和销毁,所以我们仅关注页面范围。

前面了解到,自定义 @ActivityScoped 注解和 @Singleton 注解,生成的代码完全一样。

这说明 @Scope 标记的自定义注解,实现都一样,只是命名不同而已。

考虑到这样一种设计:

  1. AccountActivity 页面中包含 LoginFragmentRegisterFragment 两个片段
  2. 这两个片段都使用 AccountModel 模型进行登录或注册操作
  3. 模型实例在两个片段之间共享,属于 @ActivityScoped 注解标记的单例
  4. 进入 AccountActivity 页面,初始化 AccountModel 模型实例
  5. 退出 AccountActivity 页面,回收 AccountModel 模型实例

可以看到,模型实例跟随页面的生命周期,朝生暮死。

如图所示:

Dagger2-Activity-@Scope.png

注意,@Scope 注解不划分功能范围,所以我们不创建名为 @AccountScoped 的注解。

5.4.3 其他范围

@ActivityScoped 注解所表示的生命周期,完全足够,不用再创建 @FragmentScoped 注解。

因为 Fragment 片段跟随 Activity 页面的生命周期,当页面销毁时,片段也随之被销毁。

即使在 Model-View-ViewModel 架构中,ViewModel 视图模型也是跟随 View 视图(即 Activity 页面)的生命周期,属于 @ActivityScoped 范围,而 Model 模型的创建成本很低,不需要设计为单例。

对于 Service、Broadcast Receiver 以及 Content Provider 三个组件来说,虽然也可以创建对应的自定义范围注解,但是由于它们的生命周期通常跟随整个应用,所以其实用 @Singleton 注解替代才是最佳选择。

综上所述,我们不需要其他范围,如果 Activity 页面不包含 Fragment 片段,连页面范围都可以省略。

5.5 总结

@Scope 通过标记自定义注解,帮助我们 划分单例所属生命周期

  • 在 Application 中,使用 @Singleton 内置注解标记全局单例
  • 在 Activity 中,使用 @ActivityScoped 自定义注解标记页面单例

可以认为,@Scope 实际上就是单例模式,只是用不同的命名表示不同的单例生效范围。

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

推荐阅读更多精彩内容