Android Jetpack庫剖析之ViewModel組件篇

前言

今天讓我們一起去探究一下ViewModel的實現原理,描述的不對或不足還請海涵,僅作為參考

ViewModel簡介

ViewModel是一個可感知Activity或Fragment生命周期的一個架構組件,當視圖銷毀,數據也會被清除,所以它的本質就是用來存儲與視圖相關的數據,讓視圖顯示控制與數據分離,即使界面配置發生改變數據也不會被銷毀,通常配合LiveData使用

ViewModel用法

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding = ActivityMainBinding.inflate(LayoutInflater.from(baseContext))
        setContentView(binding.root)
        //獲取ViewModel實例
        val viewModel: TextViewModel = ViewModelProvider(this).get(TextViewModel::class.java)
        //訂閱數據
        viewModel.liveData.observe(this, { println(it) })
        //調用函數
        viewModel.test()
    }
    class TextViewModel : ViewModel() {
        val liveData = MediatorLiveData<String>()
        fun test() {
            liveData.postValue("Hello")
        }
    }
}

1,使用ViewModelProvider獲取ViewModel實例

2,訂閱VIewModel的LiveData

3,調用ViewModel的方法

構造ViewModelProvider過程做瞭什麼

    public ViewModelProvider(@NonNull ViewModelStoreOwner owner) {
        this(owner.getViewModelStore(), owner instanceof HasDefaultViewModelProviderFactory
                ? ((HasDefaultViewModelProviderFactory) owner).getDefaultViewModelProviderFactory()
                : NewInstanceFactory.getInstance());
    }
    public ViewModelProvider(@NonNull ViewModelStore store, @NonNull Factory factory) {
        mFactory = factory;
        mViewModelStore = store;
    

1,當我們創建ViewModelProvider的時候需要傳入一個ViewModelStoreOwner對象,ViewModelStoreOwner是負責提供ViewModelStore對象的, 而ComponentActivity實現瞭這個接口,所以我們默認傳當前的Activity即可

2,首先判斷是否有默認的ViewModel工廠,如果沒有就創建一個Factory

3,Factory是用來創建ViewModel的,ViewModelStore是用來存儲ViewModel的

調用get()方法是如何構建ViewModel

    @NonNull
    @MainThread
    public <T extends ViewModel> T get(@NonNull Class<T> modelClass) {
        //獲取類名
        String canonicalName = modelClass.getCanonicalName();
        if (canonicalName == null) {
            throw new IllegalArgumentException("Local and anonymous classes can not be ViewModels");
        }
        return get(DEFAULT_KEY + ":" + canonicalName, modelClass);
    }
    @NonNull
    @MainThread
    public <T extends ViewModel> T get(@NonNull String key, @NonNull Class<T> modelClass) {
        //通過key到ViewModelStore中取
        ViewModel viewModel = mViewModelStore.get(key);
        
        //如果取到ViewModel 代表已經創建過這個ViewModel 直接返回
        if (modelClass.isInstance(viewModel)) {
            if (mFactory instanceof OnRequeryFactory) {
                ((OnRequeryFactory) mFactory).onRequery(viewModel);
            }
            return (T) viewModel;
        } else {
            //noinspection StatementWithEmptyBody
            if (viewModel != null) {
                // TODO: log a warning.
            }
        }
        //通過Factor利用反射創建一個實例
        if (mFactory instanceof KeyedFactory) {
            viewModel = ((KeyedFactory) mFactory).create(key, modelClass);
        } else {
            viewModel = mFactory.create(modelClass);
        }
        //把ViewModel實例存儲到ViewModelStore中
        mViewModelStore.put(key, viewModel);
        return (T) viewModel;
    }

1,當我們調用get()方法時會先獲取類名,然後生成一個唯一的key

2,先通過key到ViewModelStore中取ViewModel,如果不為空代表已經創建過這個ViewModel的實例,直接返回這個實例

3,如果為空就通過工廠利用java反射機制創建一個實例,通過鍵值對形式保存到ViewModelStore中,返回實例,看到這裡是不是對為什麼多個fragment可以共享同一個ViewModel的疑問豁然開朗瞭,因為Fragment是依附於Activity之上的,在我們構建ViewModelProvider的時候傳入同一個Activity,那麼ViewModelProvider得到的ViewModelStore是同一個,在我們調用get()方法時就能通過key到ViewModelStore中取到同一個ViewModel實例,說白瞭就是共用Activity的ViewModel

Activity配置發生改變如何緩存ViewModelStore

ActivityThread{
    private void handleRelaunchActivityInner(ActivityClientRecord r, int configChanges,
            List<ResultInfo> pendingResults, List<ReferrerIntent> pendingIntents,
            PendingTransactionActions pendingActions, boolean startsNotResumed,
            Configuration overrideConfig, String reason) {
        // Preserve last used intent, it may be set from Activity#setIntent().
        final Intent customIntent = r.activity.mIntent;
        // Need to ensure state is saved.
        if (!r.paused) {
            performPauseActivity(r, false, reason, null /* pendingActions */);
        }
        if (!r.stopped) {
            callActivityOnStop(r, true /* saveState */, reason);
        }
        //銷毀Activity
        handleDestroyActivity(r.token, false, configChanges, true, reason);
        //啟動Activity
        handleLaunchActivity(r, pendingActions, customIntent);
    }
}

1,當我們切換橫豎屏的時候,ActivityThread會接收到RELAUNCH_ACTIVITY消息,會調用自身的handleRelaunchActivityInner(),這個方法裡面有一個參數r,類型是ActivityClientRecord,我們每打開一個Activity,ActivityThread就會生成這麼個對象來記錄我們打開的Activity並保存起來

2,handleRelaunchActivityInner()這個方法裡調用瞭handleDestroyActivity()方法去銷毀我們的Activity

ActivityThread{
        @Override
    public void handleDestroyActivity(IBinder token, boolean finishing, int configChanges,
            boolean getNonConfigInstance, String reason) {
        //執行銷毀Activity
        ActivityClientRecord r = performDestroyActivity(token, finishing,
                configChanges, getNonConfigInstance, reason);
    }
    ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing,
            int configChanges, boolean getNonConfigInstance, String reason) {
        //通過token獲取Activity的記錄
        ActivityClientRecord r = mActivities.get(token);
        if (r != null) {
            //是否需要獲取配置實例
            if (getNonConfigInstance) {
                try {
                    //調用Activity的retainNonConfigurationInstances方法獲取配置實例
                    r.lastNonConfigurationInstances
                            = r.activity.retainNonConfigurationInstances();
                } catch (Exception e) {
                }
            }
            r.setState(ON_DESTROY);
        }
        //通過token移除這條Activity的記錄
        synchronized (mResourcesManager) {
            mActivities.remove(token);
        }
        return r;
    }
}

3,handleDestroyActivity()則直接調用瞭performDestroyActivity()方法去銷毀Activity,核心部分就是調用瞭Activity的retainNonConfigurationInstances()方法獲取瞭配置實例並復制給瞭ActivityClientRecord,把NonConfigurationInstances實例保存起來

Activity{
    NonConfigurationInstances retainNonConfigurationInstances() {
        //獲取NonConfigurationInstances對象
        Object activity = onRetainNonConfigurationInstance();
        HashMap<String, Object> children = onRetainNonConfigurationChildInstances();
        FragmentManagerNonConfig fragments = mFragments.retainNestedNonConfig();
        mFragments.doLoaderStart();
        mFragments.doLoaderStop(true);
        ArrayMap<String, LoaderManager> loaders = mFragments.retainLoaderNonConfig();
        //創建NonConfigurationInstances實例
        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;
    }
}
ComponentActivity{
    @Override
    @Nullable
    public final Object onRetainNonConfigurationInstance() {
        Object custom = onRetainCustomNonConfigurationInstance();
        //獲取ViewModelStore
        ViewModelStore viewModelStore = mViewModelStore;
        if (viewModelStore == null) {
            // No one called getViewModelStore(), so see if there was an existing
            // ViewModelStore from our last NonConfigurationInstance
            NonConfigurationInstances nc =
                    (NonConfigurationInstances) getLastNonConfigurationInstance();
            if (nc != null) {
                viewModelStore = nc.viewModelStore;
            }
        }
        if (viewModelStore == null && custom == null) {
            return null;
        }
        //創建NonConfigurationInstances實例
        NonConfigurationInstances nci = new NonConfigurationInstances();
        nci.custom = custom;
        nci.viewModelStore = viewModelStore;
        return nci;
    }
}

4, 通過查閱源碼,一層一層的往下剖析,ActivityThread是通過這樣的調用鏈來獲取我們的ViewModelStore實例並保存在ActivityClientRecord中的

Activity重建後如何恢復ViewModelStore

ActivityThread{
    private void handleRelaunchActivityInner(ActivityClientRecord r, int configChanges,
            List<ResultInfo> pendingResults, List<ReferrerIntent> pendingIntents,
            PendingTransactionActions pendingActions, boolean startsNotResumed,
            Configuration overrideConfig, String reason) {
        // Preserve last used intent, it may be set from Activity#setIntent().
        final Intent customIntent = r.activity.mIntent;
        // Need to ensure state is saved.
        if (!r.paused) {
            performPauseActivity(r, false, reason, null /* pendingActions */);
        }
        if (!r.stopped) {
            callActivityOnStop(r, true /* saveState */, reason);
        }
        //銷毀Activity
        handleDestroyActivity(r.token, false, configChanges, true, reason);
        //啟動Activity
        handleLaunchActivity(r, pendingActions, customIntent);
    }
}

1,當handleDestroyActivity執行完畢就已經把ViewModelStore的實例獲取到並存放到ActivityClientRecord中,此時就開始執行handleLaunchActivity()方法來啟動activity

2,handleLaunchActivity()這個方法也需要ActivityClientRecord這個參數,而此時ActivityClientRecord這個對象正是經過handleDestroyActivity()這個方法獲取並保存瞭ViewModelStore 實例的對象

3,handleLaunchActivity()則調用瞭performLaunchActivity()方法來啟動Activity

ActivityThread{
    @Override
    public Activity handleLaunchActivity(ActivityClientRecord r,
            PendingTransactionActions pendingActions, Intent customIntent) {
        // Make sure we are running with the most recent config.
        handleConfigurationChanged(null, null);
        //去啟動Activity
        final Activity a = performLaunchActivity(r, customIntent);
        return a;
    }
    private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        try {
            Application app = r.packageInfo.makeApplication(false, mInstrumentation);
            if (activity != null) {
                CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
                Configuration config = new Configuration(mCompatConfiguration);
                if (r.overrideConfig != null) {
                    config.updateFrom(r.overrideConfig);
                }
                if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
                        + r.activityInfo.name + " with config " + config);
                Window window = null;
                if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {
                    window = r.mPendingRemoveWindow;
                    r.mPendingRemoveWindow = null;
                    r.mPendingRemoveWindowManager = null;
                }
                appContext.setOuterContext(activity);
                //調用當前打開的Activity的attach()方法
                activity.attach(appContext, this, getInstrumentation(), r.token,
                        r.ident, app, r.intent, r.activityInfo, title, r.parent,
                        r.embeddedID, r.lastNonConfigurationInstances, config,
                        r.referrer, r.voiceInteractor, window, r.configCallback,
                        r.assistToken);
                r.activity = activity;
            }
            r.setState(ON_CREATE);
            //保存這條Activity記錄
            synchronized (mResourcesManager) {
                mActivities.put(r.token, r);
            }
        } catch (SuperNotCalledException e) {
            throw e;
        } catch (Exception e) {
        }
        return activity;
    }
}

4,通過代碼發現performLaunchActivity調用瞭當前正在打開的Activity的attach方法,而這個方法需要一個NonConfigurationInstances類型的參數,這個參數裡面就有我們的ViewModelStore實例

Activity{
     final void attach(Context context, ActivityThread aThread,
            Instrumentation instr, IBinder token, int ident,
            Application application, Intent intent, ActivityInfo info,
            CharSequence title, Activity parent, String id,
            NonConfigurationInstances lastNonConfigurationInstances,
            Configuration config, String referrer, IVoiceInteractor voiceInteractor,
            Window window, ActivityConfigCallback activityConfigCallback, IBinder assistToken) {
        attachBaseContext(context);
        mFragments.attachHost(null /*parent*/);
        //賦值給mLastNonConfigurationInstances
        mLastNonConfigurationInstances = lastNonConfigurationInstances;
        setAutofillOptions(application.getAutofillOptions());
        setContentCaptureOptions(application.getContentCaptureOptions());
    }
    public Object getLastNonConfigurationInstance() {
        return mLastNonConfigurationInstances != null
                ? mLastNonConfigurationInstances.activity : null;
    }
}
ComponentActivity{
    public ViewModelStore getViewModelStore() {
        if (getApplication() == null) {
            throw new IllegalStateException("Your activity is not yet attached to the "
                    + "Application instance. You can't request ViewModel before onCreate call.");
        }
        if (mViewModelStore == null) {
            //先去lastNonConfigurationInstance中取,沒有再創建
            NonConfigurationInstances nc =
                    (NonConfigurationInstances) getLastNonConfigurationInstance();
            if (nc != null) {
                // Restore the ViewModelStore from NonConfigurationInstances
                mViewModelStore = nc.viewModelStore;
            }
            if (mViewModelStore == null) {
                mViewModelStore = new ViewModelStore();
            }
        }
        return mViewModelStore;
    }
}

5,在attach方法裡就把這個參數賦值給mLastNonConfigurationInstances,當我們獲取ViewModelStore實例的時候,就會先去mLastNonConfigurationInstances中取,如果沒有再自己創建一個ViewModelStore實例,到這裡整個調用鏈就搞明白瞭

生命周期綁定

ComponentActivity{
    public ComponentActivity(){
        //訂閱生命周期,當生命周期==ON_DESTROY,清除ViewModel數據
        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();
                    }
                }
            }
        });
    }
}
ViewModelStore{
    public final void clear() {
        //遍歷所有ViewModel並調用其clear()方法清空數據
        for (ViewModel vm : mMap.values()) {
            vm.clear();
        }
        //清空所有ViewModel
        mMap.clear();
    }
}

總結

1,ComponentActivity實現瞭ViewModelStoreOwner接口並實現瞭其抽象方法getViewModelStore()

2,我們通過ViewModelProvider使用默認工廠創建瞭ViewModel,通過唯一key值進行標識並保存到ViewModelStore中

3,當切換橫豎屏的時候ActivityThread接收到RELAUNCH_ACTIVITY消息,就會調用Activity的retainNonConfigurationInstances()方法獲取我們的ViewModelStore實例並保存起來

4,當Activity啟動並調用attach()方法時就將切換橫豎屏前的ViewModel恢復過來

5,當我們獲取ViewModelStore實例的時候會調用先getLastNonConfigurationInstance()方法去取ViewModelStore,如果為null就會重新創建ViewModelStore並存儲在全局中

6,當生命周期發生改變,並且狀態為ON_DESTROY,清除ViewModel數據以及實例

到此這篇關於Android Jetpack庫剖析之ViewModel組件篇的文章就介紹到這瞭,更多相關Android ViewModel內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: