AndroidX Lifecycle v2.1.0 在 ViewModel 中引入 viewModelScope
,當 ViewModel 被銷燬時它會自動取消協程任務,這個特性真的好用。本文介紹 viewModelScope
使用和內部實現方式,分析 ViewModel 是如何自動取消協程的。android
當咱們在 ViewModel 裏面須要引入協程,首先要在 ViewModel 中新建一個 CoroutineScope, 用來管理全部協程任務,同時須要 onCleared()
方法裏面取消協程任務,模板代碼實現以下:ide
class MyViewModel : ViewModel() {
private val viewModelJob = SupervisorJob()
private val uiScope = CoroutineScope(Dispatchers.Main + viewModelJob)
override fun onCleared() {
super.onCleared()
viewModelJob.cancel() // Cancel all coroutines
}
fun launchDataLoad() {
uiScope.launch {
sortList()
// Modify UI
}
}
suspend fun sortList() = withContext(Dispatchers.Default) {
// Heavy work
}
}
複製代碼
然而,不少狀況咱們會常常忘記取消協程,致使出現內存泄漏等各類問題。 遇到這種場景,可使用 ViewModel 擴展屬性 viewModelScope
來優化代碼。優化
注意 lifecycle-viewmodel-ktx 版本號: 2.1.0-beta01ui
viewModelScope
管理協程的方式與咱們在 ViewModel 引入協程的方式同樣,使用很是簡單,模板代碼實現以下:this
class MyViewModel : ViewModel() {
fun launchDataLoad() {
viewModelScope.launch {
sortList()
// Modify UI
}
}
suspend fun sortList() = withContext(Dispatchers.Default) {
// Heavy work
}
}
複製代碼
// androidx.lifecycle.ViewModel.viewModelScope
private const val JOB_KEY = "androidx.lifecycle.ViewModelCoroutineScope.JOB_KEY"
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))
}
internal class CloseableCoroutineScope(context: CoroutineContext) : Closeable, CoroutineScope {
override val coroutineContext: CoroutineContext = context
override fun close() {
coroutineContext.cancel()
}
}
複製代碼
分析 viewModelScope
源碼有 3 點須要關注:spa
SupervisorJob
而不是用 Job
Closeable
接口viewModelScope
默認使用 Dispatchers.Main
, 方便 Activity 和 Fragment 更新 UIViewModel 類經過 HashMap 存儲 CoroutineScope 對象,當使用 getTag(JOB_KEY)
方法獲取對象不存在時,建立一個新的 CoroutineScope 並調用 setTagIfAbsent(JOB_KEY, scope)
方法存儲新建的 CoroutineScope 對象。ViewModel 被銷燬時內部會執行 clear()
方法,在 clear()
方法中遍歷調用 closeWithRuntimeException
取消了 viewModelScope
的協程,實現流程很是清晰。相關代碼以下:code
// androidx.lifecycle.ViewModel
// clear() -> closeWithRuntimeException() -> coroutineContext.cancel()
private final Map<String, Object> mBagOfTags = new HashMap<>();
<T> T getTag(String key) {
synchronized (mBagOfTags) {
return (T) mBagOfTags.get(key);
}
}
<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;
}
@MainThread
final void clear() {
mCleared = true;
if (mBagOfTags != null) {
for (Object value : mBagOfTags.values()) {
closeWithRuntimeException(value);
}
}
onCleared();
}
private static void closeWithRuntimeException(Object obj) {
if (obj instanceof Closeable) {
try {
((Closeable) obj).close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
複製代碼
若是你也正在使用 MVVM 和協程,很是推薦在 ViewModel 中使用 viewModelScope
方式。不只簡化 ViewModel 代碼,並且還能管理協程生命週期。協程