网站首页 > java教程 正文
前言
使用协程,相信很多同学已经信手拈来了,但是关于ViewModelScope,可能很多同学在用,但却不知道原理,今天来一探究竟。
ViewModelScope,顾名思义,在ViewModel中使用的协程。它是ViewModel的扩展属性。
推荐理由:
- 自动取消,不会造成内存泄漏,如果是CoroutineScope,就需要在onCleared()方法中手动取消了,否则可能会造成内存泄漏。
- 配合ViewModel,能减少样板代码,提高效率。
后面会重点介绍ViewModelScope是怎么做到不会内存泄漏的。
使用
引入
- 协程:
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.0'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.0'
- viewmodel-ktx:
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的使用,以及源码分析。
最后
写作不易,如果对你有一丢丢帮助或启发,感谢点赞支持 ^ - ^
猜你喜欢
- 2024-11-23 阿里P7大牛论:Kotlin协程优雅的与Retrofit缠绵
- 2024-11-23 Android技术分享|利用Kotlin协程,多任务并行,测试RTM SDK性能
- 2024-11-23 Go 的调度器是怎么实现协程中断的?远离手撕源码用 GIF 动图告诉你
- 2024-11-23 使用协程优化你的业务
- 2024-11-23 爱奇艺网络协程编写高并发应用实践
- 2024-11-23 如何用 Netty 写一个高性能的分布式服务框架?
- 2024-11-23 进程、线程、线程池和协程如何理解?
- 2024-11-23 直击灵魂!美团大牛手撸并发原理笔记,由浅入深剖析JDK源码
- 2024-11-23 Kotlin 协程一
- 2024-11-23 Kotlin 协程与架构组件一起使用及底层原理分析
你 发表评论:
欢迎- 最近发表
-
- 五,网络安全IDA Pro反汇编工具初识及逆向工程解密实战
- 「JAVA8」- Lambda 表达式(java lambda表达式原理)
- 深入探讨Java代码保护:虚拟机保护技术的新时代
- Nginx反向代理原理详解(图文全面总结)
- 逆向拆解日本IT,哪些Java技术栈薪资溢价高
- mybatis 逆向工程使用姿势不对,把表清空了,心里慌的一比
- Spring Boot集成ProGuard轻松实现Java 代码混淆, Java 应用固若金汤
- 从 Java 代码逆向工程生成 UML 类图和序列图
- 人与人相处:尊重是标配,靠谱是高配,厚道是顶配
- Windows系统安装日期如何修改(windows10怎么修改安装日期)
- 标签列表
-
- java反编译工具 (77)
- java反射 (57)
- java接口 (61)
- java随机数 (63)
- java7下载 (59)
- java数据结构 (61)
- java 三目运算符 (65)
- java对象转map (63)
- Java继承 (69)
- java字符串替换 (60)
- 快速排序java (59)
- java并发编程 (58)
- java api文档 (60)
- centos安装java (57)
- java调用webservice接口 (61)
- java深拷贝 (61)
- 工厂模式java (59)
- java代理模式 (59)
- java.lang (57)
- java连接mysql数据库 (67)
- java重载 (68)
- java 循环语句 (66)
- java反序列化 (58)
- java时间函数 (60)
- java是值传递还是引用传递 (62)
本文暂时没有评论,来添加一个吧(●'◡'●)