Loader 知識梳理(1) LoaderManager初探

1、概述

剛開始學習Loader的時候,只是使用CursorLoader把它看成加載封裝在ContentProvider中的數據的一種方式,可是若是咱們學會了如何取定義本身的Loader,那麼將不只僅侷限於讀取ContentProvider的數據,在谷歌的藍圖框架中,就有一個分支是介紹如何使用Loader來實現數據的異步讀取:android

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

咱們如今來學習一下Loader的實現原理,這將幫助咱們知道如何自定義本身的Loader來進行異步數據的加載。github

2、ActivityLoaderManager的橋樑 - FragmentHostCallback

若是咱們把Loader比喻爲異步任務的執行者,那麼LoaderManager就是這些執行者的管理者,而LoaderManager對於Loader的管理又會依賴於Activity/Fragment的生命週期。 在整個系統當中,LoaderManagerActivity/Fragment之間的關係是經過FragmentHostCallback這個中介者維繫的,當Activity或者Fragment的關鍵生命週期被回調時,會調用FragmentHostCallback的對應方法,它再經過內部持有的LoaderManager實例來控制每一個LoaderManager內的Loader。 在FragmentHostCallback當中,和Loader有關的成員變量包括:bash

/** 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的對象關係

下面是整理的表格:app

  • 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);
複製代碼

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

  • onStart時啓動Loader
  • onStop時中止Loader
  • onDestory時銷燬Loader
  • 在配置發生變化時保存Loader

3、LoaderManager/LoaderManagerImpl的含義

經過上面,咱們就能夠了解系統是怎麼根據Activity/Fragment的生命週期來自動管理Loader的了,如今,咱們來看一下LoaderManagerImpl的具體實現,這兩個類的關係是:函數

  • LoaderManager:這是一個抽象類,它內部定義了LoaderCallbacks接口,在loader的狀態發生改變時會經過這個回調通知使用者,此外,它還定義了三個關鍵的抽象方法,調用者只須要使用這三個方法就能完成數據的異步加載。
  • LoaderManagerImpl:繼承於LoaderManager,真正地實現了Loader的管理。

4、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

#5、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被替換了。

6、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();
        }
    }
複製代碼
相關文章
相關標籤/搜索