ViewModelScope简介

26 阅读1分钟

viewmodel源码简介

public abstract class ViewModel {

//hashmap 容器   
@Nullable
private final Map<String, Object> mBagOfTags = new HashMap<>();


//vm销毁时调用
protected void onCleared() {
}


@MainThread
final void clear() {
    mCleared = true;
    
    //
    if (mBagOfTags != null) {
        synchronized (mBagOfTags) {
            for (Object value : mBagOfTags.values()) {
                
                //遍历清理
                closeWithRuntimeException(value);
            }
        }
    }
    // We need the same null check here
    if (mCloseables != null) {
        synchronized (mCloseables) {
            for (Closeable closeable : mCloseables) {
                closeWithRuntimeException(closeable);
            }
        }
        mCloseables.clear();
    }
    onCleared();
}

private static void closeWithRuntimeException(Object obj) {
    if (obj instanceof Closeable) {
        try {
            //最后执行value.close()方法
            ((Closeable) obj).close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

}
public val ViewModel.viewModelScope: CoroutineScope
    get() {
    //一个viewmodel 对应一个 viewModelScope
        val scope: CoroutineScope? = this.getTag(JOB_KEY)
        if (scope != null) {
            return scope
        }
            // CloseableCoroutineScope 存储在viewmodel中的mBagOfTags中
        return setTagIfAbsent(
            JOB_KEY,
            CloseableCoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
        )
    }

CloseableCoroutineScope

//viewmodel 执行clear方法时,执行close()
internal class CloseableCoroutineScope(context: CoroutineContext) : Closeable, CoroutineScope {
    override val coroutineContext: CoroutineContext = context
    //
    override fun close() {
        //vm销毁,协程自动取消
        coroutineContext.cancel()
    }
}

总结

viewmodelScopeviewmodel的扩展函数,是预定义的 CoroutineScope 当用户离开页面,viewmodel 销毁,viewModelScope 会自动取消,且所有运行的协程也会被取消