前言
使用协程,相信很多同学已经信手拈来了,但是关于ViewModelScope,可能很多同学在用,但却不知道原理,今天来一探究竟。
ViewModelScope,顾名思义,在ViewModel中使用的协程。它是ViewModel的扩展属性。
推荐理由:
后面会重点介绍 ViewModelScope 是怎么做到不会内存泄漏的。
使用
引入
 implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.0'implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.0'
   复制代码
 
 implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1")
   复制代码
 
ViewModelScope 虽然是协程,但属于androidx.lifecycle包中 ViewModel 的扩展属性。
示例:
 class MyViewModel :ViewModel() {        fun getData(){        viewModelScope.launch {            // do        }    }    }
   复制代码
 
使用非常简单,关键在于它是怎么保证不会内存泄露的?
源码分析
来看viewModelScope源码:
 public 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)        )    }
internal class CloseableCoroutineScope(context: CoroutineContext) : Closeable, CoroutineScope {    override val coroutineContext: CoroutineContext = context
    override fun close() {        coroutineContext.cancel()    }}
   复制代码
 
先看get()方法:
 get() {    val scope: CoroutineScope? = this.getTag(JOB_KEY)    if (scope != null) {        return scope    }    return setTagIfAbsent(        JOB_KEY,        CloseableCoroutineScope(SupervisorJob() +Dispatchers.Main.immediate)    )}
   复制代码
 
return 中通过setTagIfAbsent创建了协程,并且指定主线程。
先忽略 setTagIfAbsent,来看协程创建的方式:
 internal class CloseableCoroutineScope(context: CoroutineContext) : Closeable, CoroutineScope {    override val coroutineContext: CoroutineContext = context
    override fun close() {        coroutineContext.cancel()    }}
   复制代码
 
CloseableCoroutineScope,顾名思义,可以关闭的协程。
实现Closeable接口,并重写唯一方法close(),并在方法中取消了协程。
现在我们已经知道了viewModelScope是可以取消的了,关键就在于取消时机的控制了。
回过头在再看 setTagIfAbsent,setTagIfAbsent 是ViewModel中的方法
 public abstract class ViewModel {     @Nullable    private final Map<String, Object> mBagOfTags = new HashMap<>();    private volatile boolean mCleared = false;
    @SuppressWarnings("WeakerAccess")    protected void onCleared() {    }
    @MainThread    final void clear() {        mCleared = true;         if (mBagOfTags != null) {            synchronized (mBagOfTags) {                for (Object value : mBagOfTags.values()) {                    closeWithRuntimeException(value);                }            }        }        onCleared();    }
    @SuppressWarnings("unchecked")    <T> T setTagIfAbsent(String key, T newValue) {        T previous;        synchronized (mBagOfTags) {            previous = (T) mBagOfTags.get(key);            if (previous == null) {                mBagOfTags.put(key, newValue);            }        }        T result = previous == null ? newValue : previous;        if (mCleared) {             closeWithRuntimeException(result);        }        return result;    }
    @SuppressWarnings({"TypeParameterUnusedInFormals", "unchecked"})    <T> T getTag(String key) {        if (mBagOfTags == null) {            return null;        }        synchronized (mBagOfTags) {            return (T) mBagOfTags.get(key);        }    }
    private static void closeWithRuntimeException(Object obj) {        if (obj instanceof Closeable) {            try {                ((Closeable) obj).close();            } catch (IOException e) {                throw new RuntimeException(e);            }        }    }}
   复制代码
 
在 setTagIfAbsent 中,以HashMap的形式把协程对象保存起来了,并配有 getTag 方法。
可能有同学已经注意到最后的方法closeWithRuntimeException,因为这个方法中调用了 Closeable 接口的 close()方法,而 close()方法就是用来取消协程的。
而 closeWithRuntimeException 方法是谁调用的呢,主要是 ViewModel 中的clear()方法。
     @MainThread    final void clear() {        mCleared = true;        if (mBagOfTags != null) {            synchronized (mBagOfTags) {                for (Object value : mBagOfTags.values()) {                    closeWithRuntimeException(value);                }            }        }        onCleared();    }
   复制代码
 
这里是循环保存协程的 HashMap,然后调用 closeWithRuntimeException 取消协程。
那这个 ViewModel 中的clear()方法又是谁调用的呢?
查看源码,只有一处调用,就是在ViewModelStore中
 public class ViewModelStore {
    private final HashMap<String, ViewModel> mMap = new HashMap<>();
    final void put(String key, ViewModel viewModel) {        ViewModel oldViewModel = mMap.put(key, viewModel);        if (oldViewModel != null) {            oldViewModel.onCleared();        }    }
    final ViewModel get(String key) {        return mMap.get(key);    }
    Set<String> keys() {        return new HashSet<>(mMap.keySet());    }
    public final void clear() {        for (ViewModel vm : mMap.values()) {            vm.clear();        }        mMap.clear();    }}
   复制代码
 
ViewModelStore 的源码比较少,也很简单。
同样也是以 HashMap 的形式来保存 ViewModel。
那是什么时候保存的呢,我们来追踪一下put方法:
 public class ViewModelProvider {        //...        @SuppressWarnings("unchecked")    @NonNull    @MainThread    public <T extends ViewModel> T get(@NonNull String key, @NonNull Class<T> modelClass) {        //...                mViewModelStore.put(key, viewModel);        return (T) viewModel;    }
    //...}
   复制代码
 
在ViewModelProvider的 get 方法中调用了 put,也就是说,我们在创建 ViewModel 的时候并把其保存了起来。
回过头来再看 ViewModelStore,同样也有一个clear()方法,同样循环调用vm.clear()。
继续追踪 ViewModelStore 的 clear()方法是在哪调用的。
是在ComponentActivity.java中调用的:
 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,并添加生命周期监听。
在生命周期为onDestroy的时候,获取 ViewModelStore,并调用其 clear()方法。
至此,相信大部分同学都明白了 ViewModelScope 为什么不会造成内存泄露了,因为在 onDestroy 的时候会取消执行,只不过这部分工作源码已经替我们完成了。
关于怎么获取到当前生命周期状态的,就涉及到Lifecycle相关的知识了,简而言之,不管是Activity还是Fragment,都是LifecycleOwner,其实是父类实现的,比如 ComponentActivity。在父类中通过ReportFragment或ActivityLifecycleCallbacks接口来派发当前生命周期状态,具体使用哪种派发方式要看Api等级是否在 29(10.0)及以上,及 则后者。
author:yechaoa
总结
最后,我们再来总结一下ViewModelScope的整个流程。
- 首先在创建 ViewModel 的时候,会通过 ViewModelStore 以 HashMap 的形式把 ViewModel 保存起来; 
- 随后我们在调用 viewModelScope 的时候,会在 ViewModel 中以 HashMap 的形式把协程也保存起来,而这个协程实现了 Closeable 接口,并在 Closeable 接口的 close()方法中取消协程; 
- 在 ViewModel 中有个 clear()方法,会循环调用 close()方法取消协程; 
- 在 ViewModelStore 中也有个 clear()方法,会循环调用 ViewModel 中的 clear()方法; 
- 而 ViewModelStore 中的 clear()方法,是由 Lifecycle 在生命周期执行到 onDestroy 的时候调用的。 
为避免有的同学没理解,我们再反推梳理一次
- 在生命周期执行到 onDestroy 的时候,调用 ViewModelStore 中的 clear()方法; 
- 在 ViewModelStore 中的 clear()方法中,循环调用 ViewModel 的 clear()方法; 
- 在 ViewModel 的 clear()方法中,循环调用 close()取消协程。 
ok,以上就是ViewModelScope的使用,以及源码分析。
最后
写作不易,如果对你有一丢丢帮助或启发,感谢点赞支持 ^ - ^
评论