溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Android?ViewModelScope怎么自動取消協(xié)程

發(fā)布時間:2022-07-04 09:37:57 來源:億速云 閱讀:147 作者:iii 欄目:開發(fā)技術(shù)

本文小編為大家詳細(xì)介紹“Android ViewModelScope怎么自動取消協(xié)程”,內(nèi)容詳細(xì),步驟清晰,細(xì)節(jié)處理妥當(dāng),希望這篇“Android ViewModelScope怎么自動取消協(xié)程”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學(xué)習(xí)新知識吧。

先看一下 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))
        }

可以看到這個是一個擴(kuò)展方法,

再點(diǎn)擊 setTagIfAbsent 方法進(jìn)去

 <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) {//判斷是否已經(jīng)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 內(nèi)的 mBagOfTags 中

這個 mBagOfTags 是

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

這個時候 我們 viewModel 就會持有 我們 viewModelScope 的協(xié)程 作用域了。那..這也只是 表述了 我們 viewModelScope 存在哪里而已,什么時候清除呢?

先看一下 ViewModel 的生命周期:

Android?ViewModelScope怎么自動取消協(xié)程

可以看到 ViewModel 的生命周期 會在 Activity onDestory 之后會被調(diào)用。那...具體哪里調(diào)的?

翻看源碼可以追溯到 ComponentActivity 的默認(rèn)構(gòu)造器內(nèi)

 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();
                    }
                }
            }
        });
  }

可以看到內(nèi)部會通對 Lifecycle 添加一個觀察者,觀察當(dāng)前 Activity 的生命周期變更事件,如果走到了 Destory ,并且 本次 Destory 并非由于配置變更引起的,才會真正調(diào)用 ViewModelStore 的 clear 方法。

跟進(jìn) 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 內(nèi)部實(shí)現(xiàn) 用 HashMap 存儲 ViewModel

于是在 clear 的時候,會逐個遍歷調(diào)用 clear方法,再次跟進(jìn) 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();
    }

可以發(fā)現(xiàn)我們最初 存放 viewmodelScope 的 mBagOfTags

這里面的邏輯 就是對 mBagOfTags 存儲的數(shù)據(jù) 挨個提取出來并且調(diào)用 closeWithRuntimeException

跟進(jìn) closeWithRuntimeException:

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

該方法內(nèi)會逐個判斷 對象是否實(shí)現(xiàn) Closeable 如果實(shí)現(xiàn)就會調(diào)用這個接口的 close 方法,

再回到最初 我們 viewModel 的擴(kuò)展方法那邊,看看我們 viewModelScope 的真正面目

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

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

可以明確的看到 我們的 ViewModelScope 實(shí)現(xiàn)了 Closeable 并且充寫了 close 方法,

close 方法內(nèi)的實(shí)現(xiàn) 會對 協(xié)程上下文進(jìn)行 cancel。

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

  • viewModelScope 是 ViewModel 的擴(kuò)展成員,該對象是 CloseableCoroutineScope,并且實(shí)現(xiàn)了 Closeable 接口

  • ViewModelScope 存儲在 ViewModel 的 名叫 mBagOfTags 的HashMap中 啊

  • ViewModel 存儲在 Activity 的 ViewModelStore 中,并且會監(jiān)聽 Activity 的 Lifecycle 的狀態(tài)變更,在ON_DESTROY 且 非配置變更引起的事件中 對 viewModelStore 進(jìn)行清空

  • ViewModelStore 清空會對 ViewModelStore 內(nèi)的所有 ViewModel 逐個調(diào)用 clear 方法。

  • ViewModel的clear方法會對 ViewModel的 mBagOfTags 內(nèi)存儲的對象進(jìn)行調(diào)用 close 方法(該對象需實(shí)現(xiàn)Closeable 接口)

  • 最終會會調(diào)用 我們 ViewModelScope 的實(shí)現(xiàn)類 CloseableCoroutineScope 的 close 方法中。close 方法會對協(xié)程進(jìn)行 cancel。

讀到這里,這篇“Android ViewModelScope怎么自動取消協(xié)程”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識點(diǎn)還需要大家自己動手實(shí)踐使用過才能領(lǐng)會,如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI