Loader 知識梳理(1) LoaderManager初探

澤毛發表於2017-12-21

一、概述

剛開始學習Loader的時候,只是使用CursorLoader把它當作載入封裝在ContentProvider中的資料的一種方式,但是如果我們學會了如何取定義自己的Loader,那麼將不僅僅侷限於讀取ContentProvider的資料,在谷歌的藍圖框架中,就有一個分支是介紹如何使用Loader來實現資料的非同步讀取:

https://github.com/googlesamples/android-architecture/tree/todo-mvp-loaders/

我們現在來學習一下Loader的實現原理,這將幫助我們知道如何自定義自己的Loader來進行非同步資料的載入。

二、ActivityLoaderManager的橋樑 - FragmentHostCallback

如果我們把Loader比喻為非同步任務的執行者,那麼LoaderManager就是這些執行者的管理者,而LoaderManager對於Loader的管理又會依賴於Activity/Fragment的生命週期。 在整個系統當中,LoaderManagerActivity/Fragment之間的關係是通過FragmentHostCallback這個中介者維繫的,當Activity或者Fragment的關鍵生命週期被回撥時,會呼叫FragmentHostCallback的對應方法,它再通過內部持有的LoaderManager例項來控制每個LoaderManager內的Loader。 在FragmentHostCallback當中,和Loader有關的成員變數包括:

    /** The loader managers for individual fragments [i.e. Fragment#getLoaderManager()] */
    private ArrayMap<String, LoaderManager> mAllLoaderManagers;
    /** Whether or not fragment loaders should retain their state */
    private boolean mRetainLoaders;
    /** The loader manger for the fragment host [i.e. Activity#getLoaderManager()] */
    private LoaderManagerImpl mLoaderManager;
    private boolean mCheckedForLoaderManager;
    /** Whether or not the fragment host loader manager was started */
    private boolean mLoadersStarted;
複製程式碼
  • mAllLoaderManagers:和Fragment關聯的LoaderManager,每個Fragment對應一個LoaderManager
  • mRetainLoaders:**FragmentLoader**是否要保持它們的狀態。
  • mLoaderManager:和Fragment宿主關聯的LoaderManager
  • mCheckedForLoaderManager:當Fragment的宿主的LoaderManager被建立以後,該標誌位變為true
  • mLoadersStarted:**Fragment的宿主的Loader**是否已經啟動。

FragmentHostCallbackdoXXXActivity的物件關係

下面是整理的表格:

  • restoreLoaderNonConfig <- onCreate
  • reportLoaderStart <- performStart
  • doLoaderStart <- onStart/retainNonConfigurationInstances
  • doLoaderStop(true/false) <- performStop/retainNonConfigurationInstances
  • retainLoaderNonConfig <- retainNonConfigurationInstances
  • doLoaderDestroy <- performDestroy
  • doLoaderRetain <- null

其中有個函式比較陌生,retainNonConfigurationInstances,我們看一下它的含義:

    NonConfigurationInstances retainNonConfigurationInstances() {
        Object activity = onRetainNonConfigurationInstance();
        HashMap<String, Object> children = onRetainNonConfigurationChildInstances();
        FragmentManagerNonConfig fragments = mFragments.retainNestedNonConfig();
        
        //由於要求儲存loader的狀態,所以我們需要標誌loader,為此,我們需要在將它交給下個Activity之前重啟一下loader
        mFragments.doLoaderStart();
        mFragments.doLoaderStop(true);
        ArrayMap<String, LoaderManager> loaders = mFragments.retainLoaderNonConfig();

        if (activity == null && children == null && fragments == null && loaders == null
                && mVoiceInteractor == null) {
            return null;
        }

        NonConfigurationInstances nci = new NonConfigurationInstances();
        nci.activity = activity;
        nci.children = children;
        nci.fragments = fragments;
        nci.loaders = loaders;
        if (mVoiceInteractor != null) {
            mVoiceInteractor.retainInstance();
            nci.voiceInteractor = mVoiceInteractor;
        }
        return nci;
    }
複製程式碼

我們看到,它儲存了大量的資訊,最後返回一個NonConfigurationInstances,因此我們猜測它和onSaveInstance的作用是類似的,在attach方法中,傳入了lastNonConfigurationInstances,之後我們就可以通過getLastNonConfigurationInstance來得到它,但是需要注意,這個變數在performResume之後就會清空。 通過ActivityThread的原始碼,我們可以看到,這個方法是在onStoponDestory之間呼叫的。

//呼叫onStop()
r.activity.performStop(r.mPreserveWindow);
//呼叫retainNonConfigurationInstances
r.lastNonConfigurationInstances = r.activity.retainNonConfigurationInstances();
//呼叫onDestroy().
mInstrumentation.callActivityOnDestroy(r.activity);
複製程式碼

總結下來,就是一下幾點:

  • onStart時啟動Loader
  • onStop時停止Loader
  • onDestory時銷燬Loader
  • 在配置發生變化時儲存Loader

三、LoaderManager/LoaderManagerImpl的含義

通過上面,我們就可以瞭解系統是怎麼根據Activity/Fragment的生命週期來自動管理Loader的了,現在,我們來看一下LoaderManagerImpl的具體實現,這兩個類的關係是:

  • LoaderManager:這是一個抽象類,它內部定義了LoaderCallbacks介面,在loader的狀態發生改變時會通過這個回撥通知使用者,此外,它還定義了三個關鍵的抽象方法,呼叫者只需要使用這三個方法就能完成資料的非同步載入。
  • LoaderManagerImpl:繼承於LoaderManager,真正地實現了Loader的管理。

四、LoaderManager的介面定義

public abstract class LoaderManager {
    /**
     * Callback interface for a client to interact with the manager.
     */
    public interface LoaderCallbacks<D> {
        /**
         * Instantiate and return a new Loader for the given ID.
         *
         * @param id The ID whose loader is to be created.
         * @param args Any arguments supplied by the caller.
         * @return Return a new Loader instance that is ready to start loading.
         */
        public Loader<D> onCreateLoader(int id, Bundle args);

        /**
         * Called when a previously created loader has finished its load.  Note
         * that normally an application is <em>not</em> allowed to commit fragment
         * transactions while in this call, since it can happen after an
         * activity's state is saved.  See {@link FragmentManager#beginTransaction()
         * FragmentManager.openTransaction()} for further discussion on this.
         * 
         * <p>This function is guaranteed to be called prior to the release of
         * the last data that was supplied for this Loader.  At this point
         * you should remove all use of the old data (since it will be released
         * soon), but should not do your own release of the data since its Loader
         * owns it and will take care of that.  The Loader will take care of
         * management of its data so you don't have to.  In particular:
         *
         * <ul>
         * <li> <p>The Loader will monitor for changes to the data, and report
         * them to you through new calls here.  You should not monitor the
         * data yourself.  For example, if the data is a {@link android.database.Cursor}
         * and you place it in a {@link android.widget.CursorAdapter}, use
         * the {@link android.widget.CursorAdapter#CursorAdapter(android.content.Context,
         * android.database.Cursor, int)} constructor <em>without</em> passing
         * in either {@link android.widget.CursorAdapter#FLAG_AUTO_REQUERY}
         * or {@link android.widget.CursorAdapter#FLAG_REGISTER_CONTENT_OBSERVER}
         * (that is, use 0 for the flags argument).  This prevents the CursorAdapter
         * from doing its own observing of the Cursor, which is not needed since
         * when a change happens you will get a new Cursor throw another call
         * here.
         * <li> The Loader will release the data once it knows the application
         * is no longer using it.  For example, if the data is
         * a {@link android.database.Cursor} from a {@link android.content.CursorLoader},
         * you should not call close() on it yourself.  If the Cursor is being placed in a
         * {@link android.widget.CursorAdapter}, you should use the
         * {@link android.widget.CursorAdapter#swapCursor(android.database.Cursor)}
         * method so that the old Cursor is not closed.
         * </ul>
         *
         * @param loader The Loader that has finished.
         * @param data The data generated by the Loader.
         */
        public void onLoadFinished(Loader<D> loader, D data);

        /**
         * Called when a previously created loader is being reset, and thus
         * making its data unavailable.  The application should at this point
         * remove any references it has to the Loader's data.
         *
         * @param loader The Loader that is being reset.
         */
        public void onLoaderReset(Loader<D> loader);
    }
    
    /**
     * Ensures a loader is initialized and active.  If the loader doesn't
     * already exist, one is created and (if the activity/fragment is currently
     * started) starts the loader.  Otherwise the last created
     * loader is re-used.
     *
     * <p>In either case, the given callback is associated with the loader, and
     * will be called as the loader state changes.  If at the point of call
     * the caller is in its started state, and the requested loader
     * already exists and has generated its data, then
     * callback {@link LoaderCallbacks#onLoadFinished} will
     * be called immediately (inside of this function), so you must be prepared
     * for this to happen.
     *
     * @param id A unique identifier for this loader.  Can be whatever you want.
     * Identifiers are scoped to a particular LoaderManager instance.
     * @param args Optional arguments to supply to the loader at construction.
     * If a loader already exists (a new one does not need to be created), this
     * parameter will be ignored and the last arguments continue to be used.
     * @param callback Interface the LoaderManager will call to report about
     * changes in the state of the loader.  Required.
     */
    public abstract <D> Loader<D> initLoader(int id, Bundle args,
            LoaderManager.LoaderCallbacks<D> callback);

    /**
     * Starts a new or restarts an existing {@link android.content.Loader} in
     * this manager, registers the callbacks to it,
     * and (if the activity/fragment is currently started) starts loading it.
     * If a loader with the same id has previously been
     * started it will automatically be destroyed when the new loader completes
     * its work. The callback will be delivered before the old loader
     * is destroyed.
     *
     * @param id A unique identifier for this loader.  Can be whatever you want.
     * Identifiers are scoped to a particular LoaderManager instance.
     * @param args Optional arguments to supply to the loader at construction.
     * @param callback Interface the LoaderManager will call to report about
     * changes in the state of the loader.  Required.
     */
    public abstract <D> Loader<D> restartLoader(int id, Bundle args,
            LoaderManager.LoaderCallbacks<D> callback);

    /**
     * Stops and removes the loader with the given ID.  If this loader
     * had previously reported data to the client through
     * {@link LoaderCallbacks#onLoadFinished(Loader, Object)}, a call
     * will be made to {@link LoaderCallbacks#onLoaderReset(Loader)}.
     */
    public abstract void destroyLoader(int id);

    /**
     * Return the Loader with the given id or null if no matching Loader
     * is found.
     */
    public abstract <D> Loader<D> getLoader(int id);

    /**
     * Returns true if any loaders managed are currently running and have not
     * returned data to the application yet.
     */
    public boolean hasRunningLoaders() { return false; }
}
複製程式碼

這一部分,我們先根據原始碼的註釋對這些方法有一個大概的瞭解:

  • public Loader<D> onCreateLoader(int id, Bundle args)

  • LoaderManager需要建立一個Loader時,回撥該函式來要求使用者提供一個Loader,而id為這個Loader的唯一標識。

  • public void onLoadFinished(Loader<D> loader, D data)

  • 當之前建立的Loader完成了任務之後回撥,data就是得到的資料。

  • 回撥時,可能Activity已經呼叫了onSaveInstanceState,因此不建議在其中提交Fragment事務。

  • 這個方法會保證資料資源在被釋放之前呼叫,例如,當使用CursorLoader時,LoaderManager會負責cursor的關閉。

  • LoaderManager會主動監聽資料的變化。

  • public void onLoaderReset(Loader<D> loader)

  • 當先前建立的某個Loaderreset時回撥。

  • 呼叫者應當在收到該回撥以後移除與舊Loader有關的資料。

  • public abstract <D> Loader<D> initLoader(int id, Bundle args, LoaderManager.LoaderCallbacks<D> callback)

  • 用來初始化和啟用Loaderargs一般用來放入查詢的條件。

  • 如果id對應的Loader之前不存在,那麼會建立一個新的,如果此時Activity/Fragment已經處於started狀態,那麼會啟動這個Loader

  • 如果id對應的Loader之前存在,那麼會複用之前的Loader,並且忽略Bundle引數,它僅僅是使用新的callback

  • 如果呼叫此方法時,滿足2個條件:呼叫者處於started狀態、Loader已經存在並且產生了資料,那麼onLoadFinished會立刻被回撥。

  • 這個方法一般來說應該在元件被初始化呼叫。

  • public abstract <D> Loader<D> restartLoader(int id, Bundle args, LoaderManager.LoaderCallbacks<D> callback)

  • 啟動一個新的Loader或者重新啟動一箇舊的Loader,如果此時Activity/Fragment已經處於Started狀態,那麼會開始loading過程。

  • 如果一個相同idloader之前已經存在了,那麼當新的loader完成工作之後,會銷燬舊的loader,在舊的Loader已經被destroyed之前,會回撥對應的callback

  • 因為initLoader會忽略Bundle引數,所以當我們的查詢需要依賴於bundle內的引數時,那麼就需要使用這個方法。

  • public abstract void destroyLoader(int id)

  • 停止或者移除對應idloader

  • 如果這個loader之前已經回撥過了onLoadFinished方法,那麼onLoaderReset會被回撥,引數就是要銷燬的那個Loader例項。

  • public abstract <D> Loader<D> getLoader(int id)

  • 返回對應idloader

  • public boolean hasRunningLoaders()

  • 是否有正在執行,但是沒有返回資料的loader

#五、LoaderInfo LoaderInfo 包裝了 Loader,其中包含了狀態變數提供給 LoaderManager,並且在構造時候傳入了 LoaderManager.LoaderCallbacks<Object>,這也是回撥給我們呼叫者的地方,裡面的邏輯很複雜,我們主要關注這3個方法在什麼時候被呼叫:

    final class LoaderInfo implements Loader.OnLoadCompleteListener<Object>,
            Loader.OnLoadCanceledListener<Object> {
        final int mId; //唯一標識 Loader。
        final Bundle mArgs; //查詢引數。
        LoaderManager.LoaderCallbacks<Object> mCallbacks; //給呼叫者的回撥。
        Loader<Object> mLoader;
        boolean mHaveData;
        boolean mDeliveredData;
        Object mData;
        @SuppressWarnings("hiding")
        boolean mStarted;
        @SuppressWarnings("hiding")
        boolean mRetaining;
        @SuppressWarnings("hiding")
        boolean mRetainingStarted;
        boolean mReportNextStart;
        boolean mDestroyed;
        boolean mListenerRegistered;

        LoaderInfo mPendingLoader;
        
        public LoaderInfo(int id, Bundle args, LoaderManager.LoaderCallbacks<Object> callbacks) {
            mId = id;
            mArgs = args;
            mCallbacks = callbacks;
        }
        
        void start() {
            if (mRetaining && mRetainingStarted) {
                //Activity中正在恢復狀態,所以我們什麼也不做。
                mStarted = true;
                return;
            }
            if (mStarted) {
                //已經開始了,那麼返回。
                return;
            }
            mStarted = true;
            //如果Loader沒有建立,那麼建立讓使用者去建立它。
            if (mLoader == null && mCallbacks != null) {
                mLoader = mCallbacks.onCreateLoader(mId, mArgs); //onCreateLoader()
            }
            if (mLoader != null) {
                if (mLoader.getClass().isMemberClass()
                        && !Modifier.isStatic(mLoader.getClass().getModifiers())) {
                    throw new IllegalArgumentException(
                            "Object returned from onCreateLoader must not be a non-static inner member class: "
                            + mLoader);
                }
                //註冊監聽,onLoadCanceled和OnLoadCanceledListener,因為LoaderInfo實現了這兩個介面,因此把它自己傳進去。
                if (!mListenerRegistered) {
                    mLoader.registerListener(mId, this);
                    mLoader.registerOnLoadCanceledListener(this);
                    mListenerRegistered = true;
                }
                //Loader開始工作。
                mLoader.startLoading();
            }
        }
        
        //恢復之前的狀態。
        void retain() {
            if (DEBUG) Log.v(TAG, "  Retaining: " + this);
            mRetaining = true; //正在恢復
            mRetainingStarted = mStarted; //恢復時的狀態
            mStarted = false; 
            mCallbacks = null;
        }
        
        //狀態恢復完之後呼叫。
        void finishRetain() {
            if (mRetaining) {
                if (DEBUG) Log.v(TAG, "  Finished Retaining: " + this);
                mRetaining = false;
                if (mStarted != mRetainingStarted) {
                    if (!mStarted) {
                        //如果在恢復完後發現,它已經不處於Started狀態,那麼停止。
                        stop();
                    }
                }
            }

            if (mStarted && mHaveData && !mReportNextStart) {
                // This loader has retained its data, either completely across
                // a configuration change or just whatever the last data set
                // was after being restarted from a stop, and now at the point of
                // finishing the retain we find we remain started, have
                // our data, and the owner has a new callback...  so
                // let's deliver the data now.
                callOnLoadFinished(mLoader, mData);
            }
        }
        
        void reportStart() {
            if (mStarted) {
                if (mReportNextStart) {
                    mReportNextStart = false;
                    if (mHaveData) {
                        callOnLoadFinished(mLoader, mData);
                    }
                }
            }
        }

        void stop() {
            if (DEBUG) Log.v(TAG, "  Stopping: " + this);
            mStarted = false;
            if (!mRetaining) {
                if (mLoader != null && mListenerRegistered) {
                    // Let the loader know we're done with it
                    mListenerRegistered = false;
                    mLoader.unregisterListener(this);
                    mLoader.unregisterOnLoadCanceledListener(this);
                    mLoader.stopLoading();
                }
            }
        }

        void cancel() {
            if (DEBUG) Log.v(TAG, "  Canceling: " + this);
            if (mStarted && mLoader != null && mListenerRegistered) {
                if (!mLoader.cancelLoad()) {
                    onLoadCanceled(mLoader);
                }
            }
        }

        void destroy() {
            if (DEBUG) Log.v(TAG, "  Destroying: " + this);
            mDestroyed = true;
            boolean needReset = mDeliveredData;
            mDeliveredData = false;
            if (mCallbacks != null && mLoader != null && mHaveData && needReset) {
                if (DEBUG) Log.v(TAG, "  Reseting: " + this);
                String lastBecause = null;
                if (mHost != null) {
                    lastBecause = mHost.mFragmentManager.mNoTransactionsBecause;
                    mHost.mFragmentManager.mNoTransactionsBecause = "onLoaderReset";
                }
                try {
                    mCallbacks.onLoaderReset(mLoader);
                } finally {
                    if (mHost != null) {
                        mHost.mFragmentManager.mNoTransactionsBecause = lastBecause;
                    }
                }
            }
            mCallbacks = null;
            mData = null;
            mHaveData = false;
            if (mLoader != null) {
                if (mListenerRegistered) {
                    mListenerRegistered = false;
                    mLoader.unregisterListener(this);
                    mLoader.unregisterOnLoadCanceledListener(this);
                }
                mLoader.reset();
            }
            if (mPendingLoader != null) {
                mPendingLoader.destroy();
            }
        }

        @Override
        public void onLoadCanceled(Loader<Object> loader) {
            if (DEBUG) Log.v(TAG, "onLoadCanceled: " + this);

            if (mDestroyed) {
                if (DEBUG) Log.v(TAG, "  Ignoring load canceled -- destroyed");
                return;
            }

            if (mLoaders.get(mId) != this) {
                // This cancellation message is not coming from the current active loader.
                // We don't care about it.
                if (DEBUG) Log.v(TAG, "  Ignoring load canceled -- not active");
                return;
            }

            LoaderInfo pending = mPendingLoader;
            if (pending != null) {
                // There is a new request pending and we were just
                // waiting for the old one to cancel or complete before starting
                // it.  So now it is time, switch over to the new loader.
                if (DEBUG) Log.v(TAG, "  Switching to pending loader: " + pending);
                mPendingLoader = null;
                mLoaders.put(mId, null);
                destroy();
                installLoader(pending);
            }
        }

        @Override
        public void onLoadComplete(Loader<Object> loader, Object data) {
            if (DEBUG) Log.v(TAG, "onLoadComplete: " + this);
            
            if (mDestroyed) {
                if (DEBUG) Log.v(TAG, "  Ignoring load complete -- destroyed");
                return;
            }

            if (mLoaders.get(mId) != this) {
                // This data is not coming from the current active loader.
                // We don't care about it.
                if (DEBUG) Log.v(TAG, "  Ignoring load complete -- not active");
                return;
            }
            
            LoaderInfo pending = mPendingLoader;
            if (pending != null) {
                // There is a new request pending and we were just
                // waiting for the old one to complete before starting
                // it.  So now it is time, switch over to the new loader.
                if (DEBUG) Log.v(TAG, "  Switching to pending loader: " + pending);
                mPendingLoader = null;
                mLoaders.put(mId, null);
                destroy();
                installLoader(pending);
                return;
            }
            
            // Notify of the new data so the app can switch out the old data before
            // we try to destroy it.
            if (mData != data || !mHaveData) {
                mData = data;
                mHaveData = true;
                if (mStarted) {
                    callOnLoadFinished(loader, data);
                }
            }

            //if (DEBUG) Log.v(TAG, "  onLoadFinished returned: " + this);

            // We have now given the application the new loader with its
            // loaded data, so it should have stopped using the previous
            // loader.  If there is a previous loader on the inactive list,
            // clean it up.
            LoaderInfo info = mInactiveLoaders.get(mId);
            if (info != null && info != this) {
                info.mDeliveredData = false;
                info.destroy();
                mInactiveLoaders.remove(mId);
            }

            if (mHost != null && !hasRunningLoaders()) {
                mHost.mFragmentManager.startPendingDeferredFragments();
            }
        }

        void callOnLoadFinished(Loader<Object> loader, Object data) {
            if (mCallbacks != null) {
                String lastBecause = null;
                if (mHost != null) {
                    lastBecause = mHost.mFragmentManager.mNoTransactionsBecause;
                    mHost.mFragmentManager.mNoTransactionsBecause = "onLoadFinished";
                }
                try {
                    if (DEBUG) Log.v(TAG, "  onLoadFinished in " + loader + ": "
                            + loader.dataToString(data));
                    mCallbacks.onLoadFinished(loader, data);
                } finally {
                    if (mHost != null) {
                        mHost.mFragmentManager.mNoTransactionsBecause = lastBecause;
                    }
                }
                mDeliveredData = true;
            }
        }
        
    }
複製程式碼

onCreateLoader:在 start() 方法中,如果我們發現 mLoader 沒有建立,那麼通知呼叫者建立它。

onLoaderReset:在 destroy() 方法中,也就是Loader被銷燬時呼叫,它的呼叫需要滿足以下條件:

  • mHaveData == true:mHaveData 被置為 true 的地方是在 onLoadComplete 中判斷到有新的資料,並且之前 mHaveData == false,在 onDestroy 時置為 false
  • mDeliveredData == true:它在 callOnLoadFinished 時被置為 true,成功地回撥了呼叫者的 onLoadFinished
  • 這兩個條件一結合,就可以知道這是一個已經遞交過資料的loader,所以在destory的時候,就要通知呼叫者loader被替換了。

六、LoaderManagerImpl實現的三個關鍵方法

6.1 initLoader的實現

public <D> Loader<D> initLoader(int id, Bundle args, LoaderManager.LoaderCallbacks<D> callback) {
    //createAndInstallLoader方法正在執行,丟擲異常。
    if (mCreatingLoader) {    
        throw new IllegalStateException("Called while creating a loader");
    }
    LoaderInfo info = mLoaders.get(id);
    if (info == null) {
        info = createAndInstallLoader(id, args,  (LoaderManager.LoaderCallbacks<Object>)callback);
    } else {
        info.mCallbacks = (LoaderManager.LoaderCallbacks<Object>)callback;
    }
    //如果已經有資料,並且處於LoaderManager處於Started狀態,那麼立刻返回。
    if (info.mHaveData && mStarted) {
        info.callOnLoadFinished(info.mLoader, info.mData);
    }
    return (Loader<D>) info.mLoader;
}

private LoaderInfo createAndInstallLoader(int id, Bundle args, LoaderManager.LoaderCallbacks<Object> callback) {    
    try {        
        mCreatingLoader = true; 
        //呼叫者建立loader,在主執行緒中執行。       
        LoaderInfo info = createLoader(id, args, callback);        
        installLoader(info);        
        return info;    
    } finally {        
        mCreatingLoader = false;    
    }
}

private LoaderInfo createLoader(int id, Bundle args, LoaderManager.LoaderCallbacks<Object> callback) {    
    LoaderInfo info = new LoaderInfo(id, args,  callback);   
    Loader<Object> loader = callback.onCreateLoader(id, args);    
    info.mLoader = loader;    
    return info;
}

void installLoader(LoaderInfo info) {
    mLoaders.put(info.mId, info);
    //如果已經處於mStarted狀態,說明錯過了doStart方法,那麼只有自己啟動了。
    if (mStarted) {
        info.start();
    }
}
複製程式碼

6.2 restartLoader的實現

    public <D> Loader<D> restartLoader(int id, Bundle args, LoaderManager.LoaderCallbacks<D> callback) {
        if (mCreatingLoader) {
            throw new IllegalStateException("Called while creating a loader");
        }
        
        LoaderInfo info = mLoaders.get(id);
        if (DEBUG) Log.v(TAG, "restartLoader in " + this + ": args=" + args);
        if (info != null) {
            //這個mInactive列表是restartLoader的關鍵。
            LoaderInfo inactive = mInactiveLoaders.get(id);
            if (inactive != null) {
                //如果info已經有了資料,那麼取消它。
                if (info.mHaveData) {
                    if (DEBUG) Log.v(TAG, "  Removing last inactive loader: " + info);
                    inactive.mDeliveredData = false;
                    inactive.destroy();
                    info.mLoader.abandon();
                    mInactiveLoaders.put(id, info);
                } else {
                    //info沒有開始,那麼直接把它移除。
                    if (!info.mStarted) {
                        if (DEBUG) Log.v(TAG, "  Current loader is stopped; replacing");
                        mLoaders.put(id, null);
                        info.destroy();
                    //info已經開始了。
                    } else {
                        //先取消。
                        info.cancel();
                        if (info.mPendingLoader != null) {
                            if (DEBUG) Log.v(TAG, "  Removing pending loader: " + info.mPendingLoader);
                            info.mPendingLoader.destroy();
                            info.mPendingLoader = null;
                        }
                        //inactive && !mHaveData && mStarted,那麼最新的Loader儲存在mPendingLoader這個變數當中。
                        info.mPendingLoader = createLoader(id, args, 
                                (LoaderManager.LoaderCallbacks<Object>) callback);
                        return (Loader<D>) info.mPendingLoader.mLoader;
                    }
                }
            //如果呼叫restartLoader時已經有了相同id的Loader,那麼儲存在這個列表中進行跟蹤。
            } else {
                info.mLoader.abandon();
                mInactiveLoaders.put(id, info);
            }
        }
        
        info = createAndInstallLoader(id, args,  (LoaderManager.LoaderCallbacks<Object>)callback);
        return (Loader<D>) info.mLoader;
    }
複製程式碼

程式碼的邏輯比較複雜,我們理一理:

  • mLoaders中不存在相同idLoaderInfo情況下,initLoaderrestartLoader的行為是一致的。
  • mLoaders中存在相同idLoaderInfo情況下:
  • initLoader不會新建LoaderInfo,也不會改變Bundle的值,僅僅是替換info.mCallbacks的例項。
  • restartLoader除了會新建一個全新的Loader之外,還會有這麼一套邏輯,它主要和 mInactiveLoaders以及它內部LoaderInfo所處的狀態有關有關,這個列表用來跟蹤呼叫者希望替換的舊LoaderInfo
    • 如果要被替換的LoaderInfo沒有被跟蹤,那麼呼叫info.mLoader.abandon(),再把它加入到跟蹤列表,然後會新建一個全新的LoaderInfo放入mLoaders
    • 如果要替換的LoaderInfo還處在被跟蹤的狀態,那麼再去判斷它內部的狀態:
    • 已經有資料,呼叫info.destroy()info.mLoader.abandon(),並繼續跟蹤。
    • 沒有資料:
      • 還沒有開始,呼叫info.destroy(),直接在mLoaders中把對應id的位置置為null
      • 已經開始了,那麼先info.cancel(),然後把新建的Loader賦值給LoaderInfo.mPendingLoader ,這時候mLoaders中就有兩個Loader了,這是唯一沒有新建LoaderInfo的情況,即希望替換但是還沒有執行完畢的Loader以及這個新建立的Loader

6.3 destroyLoader的實現

    public void destroyLoader(int id) {
        if (mCreatingLoader) {
            throw new IllegalStateException("Called while creating a loader");
        }
        
        if (DEBUG) Log.v(TAG, "destroyLoader in " + this + " of " + id);
        int idx = mLoaders.indexOfKey(id);
        if (idx >= 0) {
            LoaderInfo info = mLoaders.valueAt(idx);
            mLoaders.removeAt(idx);
            info.destroy();
        }
        idx = mInactiveLoaders.indexOfKey(id);
        if (idx >= 0) {
            LoaderInfo info = mInactiveLoaders.valueAt(idx);
            mInactiveLoaders.removeAt(idx);
            info.destroy();
        }
        if (mHost != null && !hasRunningLoaders()) {
            mHost.mFragmentManager.startPendingDeferredFragments();
        }
    }
複製程式碼

相關文章