一文了解Android ViewModelScope 如何自动取消协程

 更新时间:2022年07月03日 10:43:41   作者:​ 阿锅阿锅     ​  
这篇文章主要介绍了一文了解Android ViewModelScope 如何自动取消协程,文章围绕主题站展开详细的内容介绍,具有一定参考价值,感兴趣的小伙伴可以参考一下

先看一下 ViewModel 中的 ViewModelScope 是何方神圣

val ViewModel.viewModelScope: CoroutineScope
        get() {
            val scope: CoroutineScope? = this.getTag(JOB_KEY)
            if (scope != null) {
                return scope
            }
            return setTagIfAbsent(JOB_KEY,
                CloseableCoroutineScope(SupervisorJob() + Dispatchers.Main.immediate))
        }

可以看到这个是一个扩展方法,

再点击 setTagIfAbsent 方法进去

 <T> T setTagIfAbsent(String key, T newValue) {
        T previous;
        synchronized (mBagOfTags) {
            previous = (T) mBagOfTags.get(key);//第一次肯定为null
            if (previous == null) {
                mBagOfTags.put(key, newValue);//null 存储
            }
        }
        T result = previous == null ? newValue : previous;
        if (mCleared) {//判断是否已经clear了
            // It is possible that we'll call close() multiple times on the same object, but
            // Closeable interface requires close method to be idempotent:
            // "if the stream is already closed then invoking this method has no effect." (c)
            closeWithRuntimeException(result);
        }
        return result;
    }

可以看到 这边 会把 我们的 ViewModel 存储到 ViewModel 内的 mBagOfTags 中

这个 mBagOfTags 是

    private final Map<String, Object> mBagOfTags = new HashMap<>();

这个时候 我们 viewModel 就会持有 我们 viewModelScope 的协程 作用域了。那..这也只是 表述了 我们 viewModelScope 存在哪里而已,什么时候清除呢?

先看一下 ViewModel 的生命周期:

可以看到 ViewModel 的生命周期 会在 Activity onDestory 之后会被调用。那...具体哪里调的?

翻看源码可以追溯到 ComponentActivity 的默认构造器内

 public ComponentActivity() {
     /*省略一些*/
        getLifecycle().addObserver(new LifecycleEventObserver() {
            @Override
            public void onStateChanged(@NonNull LifecycleOwner source,
                    @NonNull Lifecycle.Event event) {
                if (event == Lifecycle.Event.ON_DESTROY) {
                    if (!isChangingConfigurations()) {
                        getViewModelStore().clear();
                    }
                }
            }
        });
  }

可以看到内部会通对 Lifecycle 添加一个观察者,观察当前 Activity 的生命周期变更事件,如果走到了 Destory ,并且 本次 Destory 并非由于配置变更引起的,才会真正调用 ViewModelStore 的 clear 方法。

跟进 clear 方法看看:

public class ViewModelStore {
    private final HashMap<String, ViewModel> mMap = new HashMap<>();

    /**
     *  Clears internal storage and notifies ViewModels that they are no longer used.
     */
    public final void clear() {
        for (ViewModel vm : mMap.values()) {
            vm.clear();
        }
        mMap.clear();
    }
}

可以看到这个 ViewModelStore 内部实现 用 HashMap 存储 ViewModel

于是在 clear 的时候,会逐个遍历调用 clear方法,再次跟进 ViewModel 的 clear 方法

 @MainThread
    final void clear() {
        mCleared = true;
        // Since clear() is final, this method is still called on mock objects
        // and in those cases, mBagOfTags is null. It'll always be empty though
        // because setTagIfAbsent and getTag are not final so we can skip
        // clearing it
        if (mBagOfTags != null) {
            synchronized (mBagOfTags) {
                for (Object value : mBagOfTags.values()) {
                    // see comment for the similar call in setTagIfAbsent
                    closeWithRuntimeException(value);
                }
            }
        }
        onCleared();
    }

可以发现我们最初 存放 viewmodelScope 的 mBagOfTags

这里面的逻辑 就是对 mBagOfTags 存储的数据 挨个提取出来并且调用 closeWithRuntimeException

跟进 closeWithRuntimeException:

 private static void closeWithRuntimeException(Object obj) {
        if (obj instanceof Closeable) {
            try {
                ((Closeable) obj).close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

该方法内会逐个判断 对象是否实现 Closeable 如果实现就会调用这个接口的 close 方法,

再回到最初 我们 viewModel 的扩展方法那边,看看我们 viewModelScope 的真正面目

internal class CloseableCoroutineScope(context: CoroutineContext) 
    : Closeable, CoroutineScope {
    override val coroutineContext: CoroutineContext = context

    override fun close() {
        coroutineContext.cancel()
    }
}

可以明确的看到 我们的 ViewModelScope 实现了 Closeable 并且充写了 close 方法,

close 方法内的实现 会对 协程上下文进行 cancel。

至此我们 可以大致整理一下:

  • viewModelScope 是 ViewModel 的扩展成员,该对象是 CloseableCoroutineScope,并且实现了 Closeable 接口
  • ViewModelScope 存储在 ViewModel 的 名叫 mBagOfTags 的HashMap中 啊
  • ViewModel 存储在 Activity 的 ViewModelStore 中,并且会监听 Activity 的 Lifecycle 的状态变更,在ON_DESTROY 且 非配置变更引起的事件中 对 viewModelStore 进行清空
  • ViewModelStore 清空会对 ViewModelStore 内的所有 ViewModel 逐个调用 clear 方法。
  • ViewModel的clear方法会对 ViewModel的 mBagOfTags 内存储的对象进行调用 close 方法(该对象需实现Closeable 接口)
  • 最终会会调用 我们 ViewModelScope 的实现类 CloseableCoroutineScope 的 close 方法中。close 方法会对协程进行 cancel。

到此这篇关于一文了解Android ViewModelScope 如何自动取消协程的文章就介绍到这了,更多相关Android ViewModel Scope 取消协程内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Android中不支持动态申请权限的原因

    Android中不支持动态申请权限的原因

    这篇文章主要介绍了Android中不支持动态申请权限的原因,本文列举了几个不支持动态申请权限的原因,需要的朋友可以参考下
    2015-01-01
  • android使用DataBinding来设置空状态

    android使用DataBinding来设置空状态

    本篇文章主要介绍了android使用DataBinding来设置空状态,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。
    2017-03-03
  • Android 中WebView 截图的实现方式

    Android 中WebView 截图的实现方式

    这篇文章主要介绍了Android 中WebView 截图的实现方式,WebView 作为一种特殊的控件,自然不能像其他系统 View 或者截屏的方式来获取截图。本文通过实例代码给大家介绍的非常详细,需要的朋友参考下吧
    2017-12-12
  • Android Service判断设备联网状态详解

    Android Service判断设备联网状态详解

    本文主要介绍Android Service判断联网状态,这里提供了相关资料并附有示例代码,有兴趣的小伙伴可以参考下,帮助开发相关应用功能
    2016-08-08
  • Android开发案例手册Application跳出dialog

    Android开发案例手册Application跳出dialog

    这篇文章主要为大家介绍了Android开发案例手册Application跳出dialog,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-06-06
  • Android通过单点触摸移动图片

    Android通过单点触摸移动图片

    这篇文章主要为大家详细介绍了Android通过单点触摸移动图片,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-04-04
  • Android实现调用摄像头

    Android实现调用摄像头

    本文给大家分享的是,在安卓APP开发的过程中,经常会需要调用手机自身摄像头拍照的代码,十分的简单实用,有需要的小伙伴可以参考下。
    2015-07-07
  • android不同activity之间共享数据解决方法

    android不同activity之间共享数据解决方法

    最近做局域网socket连接问题,要在多个activity之间公用一个socket连接,就在网上搜了下资料,感觉还是application方法好用,帖出来需要的朋友可以参考下
    2012-11-11
  • Android加载Gif动画实现代码

    Android加载Gif动画实现代码

    这篇文章主要为大家详细介绍了Android加载Gif动画实现代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2016-10-10
  • android Watchdog 实现剖析

    android Watchdog 实现剖析

    Android提供了Watchdog类,用来监测Service是否处于正常工作中,是在SystemServer中启动的;本文将详细介绍
    2012-11-11

最新评论