Android AAC架构解析

作者: 帽子lucio | 来源:发表于2018-10-08 10:46 被阅读50次
    • LiveData如何实现数据更新 https://www.jianshu.com/p/334d674cf65b
    • LiveData如何实现同activity声明周期绑定
    • viewModel如何实现数据共享
    • viewModel如何实现数据保存

    本文就如上问题结合aac框架源码进行逐步解析

    一.LiveData实现数据更新

    既然是监测数据更新,肯定是使用到观察者模式

    • 观察者 GenericLifecycleObserver,其中LifecycleObserver为空接口
    public interface GenericLifecycleObserver extends LifecycleObserver {
        void onStateChanged(LifecycleOwner source, Lifecycle.Event event);
    }
    
    • 被观察者
    public abstract class Lifecycle {
        
        public abstract void addObserver(@NonNull LifecycleObserver observer);
    
        @MainThread
        public abstract void removeObserver(@NonNull LifecycleObserver observer);
    
        @MainThread
        @NonNull
        public abstract State getCurrentState();
    
        @SuppressWarnings("WeakerAccess")
        public enum Event {
            /**
             * Constant for onCreate event of the {@link LifecycleOwner}.
             */
            ON_CREATE,
            /**
             * Constant for onStart event of the {@link LifecycleOwner}.
             */
            ON_START,
            /**
             * Constant for onResume event of the {@link LifecycleOwner}.
             */
            ON_RESUME,
            /**
             * Constant for onPause event of the {@link LifecycleOwner}.
             */
            ON_PAUSE,
            /**
             * Constant for onStop event of the {@link LifecycleOwner}.
             */
            ON_STOP,
            /**
             * Constant for onDestroy event of the {@link LifecycleOwner}.
             */
            ON_DESTROY,
            /**
             * An {@link Event Event} constant that can be used to match all events.
             */
            ON_ANY
        }
    
        /**
         * Lifecycle states. You can consider the states as the nodes in a graph and
         * {@link Event}s as the edges between these nodes.
         */
        @SuppressWarnings("WeakerAccess")
        public enum State {
            /**
             * Destroyed state for a LifecycleOwner. After this event, this Lifecycle will not dispatch
             * any more events. For instance, for an {@link android.app.Activity}, this state is reached
             * <b>right before</b> Activity's {@link android.app.Activity#onDestroy() onDestroy} call.
             */
            DESTROYED,
    
            /**
             * Initialized state for a LifecycleOwner. For an {@link android.app.Activity}, this is
             * the state when it is constructed but has not received
             * {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} yet.
             */
            INITIALIZED,
    
            /**
             * Created state for a LifecycleOwner. For an {@link android.app.Activity}, this state
             * is reached in two cases:
             * <ul>
             *     <li>after {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} call;
             *     <li><b>right before</b> {@link android.app.Activity#onStop() onStop} call.
             * </ul>
             */
            CREATED,
    
            /**
             * Started state for a LifecycleOwner. For an {@link android.app.Activity}, this state
             * is reached in two cases:
             * <ul>
             *     <li>after {@link android.app.Activity#onStart() onStart} call;
             *     <li><b>right before</b> {@link android.app.Activity#onPause() onPause} call.
             * </ul>
             */
            STARTED,
    
            /**
             * Resumed state for a LifecycleOwner. For an {@link android.app.Activity}, this state
             * is reached after {@link android.app.Activity#onResume() onResume} is called.
             */
            RESUMED;
    
            /**
             * Compares if this State is greater or equal to the given {@code state}.
             *
             * @param state State to compare with
             * @return true if this State is greater or equal to the given {@code state}
             */
            public boolean isAtLeast(@NonNull State state) {
                return compareTo(state) >= 0;
            }
        }
    }
    
    

    我们来看看Lifecycle实现类LifecycleRegistry,
    主要看添加观察者以及接收被观察者,对应如下两个方法

    @Override
        public void addObserver(@NonNull LifecycleObserver observer) {
            State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
            ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
            ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
    
            if (previous != null) {
                return;
            }
            LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
            if (lifecycleOwner == null) {
                // it is null we should be destroyed. Fallback quickly
                return;
            }
    
            boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
            State targetState = calculateTargetState(observer);
            mAddingObserverCounter++;
            while ((statefulObserver.mState.compareTo(targetState) < 0
                    && mObserverMap.contains(observer))) {
                pushParentState(statefulObserver.mState);
                statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState));
                popParentState();
                // mState / subling may have been changed recalculate
                targetState = calculateTargetState(observer);
            }
    
            if (!isReentrance) {
                // we do sync only on the top level.
                sync();
            }
            mAddingObserverCounter--;
        }
    
    public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
            State next = getStateAfter(event);
            moveToState(next);
        }
    

    接着看看ObserverWithState带状态的Observe做了什么,

    static class ObserverWithState {
            State mState;
            GenericLifecycleObserver mLifecycleObserver;
    
            ObserverWithState(LifecycleObserver observer, State initialState) {
                mLifecycleObserver = Lifecycling.getCallback(observer);
                mState = initialState;
            }
    
            void dispatchEvent(LifecycleOwner owner, Event event) {
                State newState = getStateAfter(event);
                mState = min(mState, newState);
                mLifecycleObserver.onStateChanged(owner, event);
                mState = newState;
            }
        }
    

    主要是Lifecycling.getCallback(observer)获取GenericLifecycleObserver,在dispatchEvent执行onStateChanged()通知数据更新,而dispatchEvent方法在addObserver中执行

    statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState));
    

    所以当liveData中执行observe时

      @MainThread
        public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<T> observer) {
            if (owner.getLifecycle().getCurrentState() == DESTROYED) {
                // ignore
                return;
            }
            LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer);
            ObserverWrapper existing = mObservers.putIfAbsent(observer, wrapper);
            if (existing != null && !existing.isAttachedTo(owner)) {
                throw new IllegalArgumentException("Cannot add the same observer"
                        + " with different lifecycles");
            }
            if (existing != null) {
                return;
            }
            owner.getLifecycle().addObserver(wrapper);
        }
    

    首先会创建LifecycleBoundObserver,来看看LifecycleBoundObserver代码

    class LifecycleBoundObserver extends ObserverWrapper implements GenericLifecycleObserver {
            @NonNull final LifecycleOwner mOwner;
    
            LifecycleBoundObserver(@NonNull LifecycleOwner owner, Observer<T> observer) {
                super(observer);
                mOwner = owner;
            }
    
            @Override
            boolean shouldBeActive() {
                return mOwner.getLifecycle().getCurrentState().isAtLeast(STARTED);
            }
    
            @Override
            public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
                if (mOwner.getLifecycle().getCurrentState() == DESTROYED) {
                    removeObserver(mObserver);
                    return;
                }
                activeStateChanged(shouldBeActive());
            }
    
            @Override
            boolean isAttachedTo(LifecycleOwner owner) {
                return mOwner == owner;
            }
    
            @Override
            void detachObserver() {
                mOwner.getLifecycle().removeObserver(this);
            }
        }
    

    LifecycleBoundObserver实现了GenericLifecycleObserver,并实现onStateChanged方法
    接着 owner.getLifecycle().addObserver(wrapper),获取Lifecycle,调用到上面解析的addObserver,
    而这里的wrapper为GenericLifecycleObserver,那么Lifecycling.getCallback(observe)直接取到GenericLifecycleObserver,则执行addObserver中dispatchEvent,即调用到onStateChanged,
    此时LifecycleBoundObserver中onStateChanged

    if (mOwner.getLifecycle().getCurrentState() == DESTROYED) 此判断解决内存泄漏问题

    @Override
            public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
                if (mOwner.getLifecycle().getCurrentState() == DESTROYED) {
                    removeObserver(mObserver);
                    return;
                }
                activeStateChanged(shouldBeActive());
            }
    

    接着执行如下,主要看dispatchingValue

      void activeStateChanged(boolean newActive) {
                if (newActive == mActive) {
                    return;
                }
                // immediately set active state, so we'd never dispatch anything to inactive
                // owner
                mActive = newActive;
                boolean wasInactive = LiveData.this.mActiveCount == 0;
                LiveData.this.mActiveCount += mActive ? 1 : -1;
                if (wasInactive && mActive) {
                    onActive();
                }
                if (LiveData.this.mActiveCount == 0 && !mActive) {
                    onInactive();
                }
                if (mActive) {
                    dispatchingValue(this);
                }
            }
    
     private void dispatchingValue(@Nullable ObserverWrapper initiator) {
            if (mDispatchingValue) {
                mDispatchInvalidated = true;
                return;
            }
            mDispatchingValue = true;
            do {
                mDispatchInvalidated = false;
                if (initiator != null) {
                    considerNotify(initiator);
                    initiator = null;
                } else {
                    for (Iterator<Map.Entry<Observer<T>, ObserverWrapper>> iterator =
                            mObservers.iteratorWithAdditions(); iterator.hasNext(); ) {
                        considerNotify(iterator.next().getValue());
                        if (mDispatchInvalidated) {
                            break;
                        }
                    }
                }
            } while (mDispatchInvalidated);
            mDispatchingValue = false;
        }
    

    这里主要看considerNotify,initiator不为null,直接调用

    private void considerNotify(ObserverWrapper observer) {
            if (!observer.mActive) {
                return;
            }
            // Check latest state b4 dispatch. Maybe it changed state but we didn't get the event yet.
            //
            // we still first check observer.active to keep it as the entrance for events. So even if
            // the observer moved to an active state, if we've not received that event, we better not
            // notify for a more predictable notification order.
            if (!observer.shouldBeActive()) {
                observer.activeStateChanged(false);
                return;
            }
            if (observer.mLastVersion >= mVersion) {
                return;
            }
            observer.mLastVersion = mVersion;
            //noinspection unchecked
            observer.mObserver.onChanged((T) mData);
        }
    

    最终执行到observer的onChanged,即public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<T> observer)中Observer的onChanged

    推展:setValue,postValue之后observer获取到数据更新

     @MainThread
        protected void setValue(T value) {
            assertMainThread("setValue");
            mVersion++;
            mData = value;
            dispatchingValue(null);
        }
    
    private void dispatchingValue(@Nullable ObserverWrapper initiator) {
            if (mDispatchingValue) {
                mDispatchInvalidated = true;
                return;
            }
            mDispatchingValue = true;
            do {
                mDispatchInvalidated = false;
                if (initiator != null) {
                    considerNotify(initiator);
                    initiator = null;
                } else {
                    for (Iterator<Map.Entry<Observer<T>, ObserverWrapper>> iterator =
                            mObservers.iteratorWithAdditions(); iterator.hasNext(); ) {
                        considerNotify(iterator.next().getValue());
                        if (mDispatchInvalidated) {
                            break;
                        }
                    }
                }
            } while (mDispatchInvalidated);
            mDispatchingValue = false;
        }
    

    同上逻辑,只是 dispatchingValue(null);会遍历所有Observer,调用considerNotify

     protected void postValue(T value) {
            boolean postTask;
            synchronized (mDataLock) {
                postTask = mPendingData == NOT_SET;
                mPendingData = value;
            }
            if (!postTask) {
                return;
            }
            ArchTaskExecutor.getInstance().postToMainThread(mPostValueRunnable);
        }
    
    private final Runnable mPostValueRunnable = new Runnable() {
            @Override
            public void run() {
                Object newValue;
                synchronized (mDataLock) {
                    newValue = mPendingData;
                    mPendingData = NOT_SET;
                }
                //noinspection unchecked
                setValue((T) newValue);
            }
        };
    

    而postValue只是post到主线程,执行setValue

    二.LiveData绑定activity声明周期

    主要看LifecycleDispatcher这个类

     static void init(Context context) {
            if (sInitialized.getAndSet(true)) {
                return;
            }
            ((Application) context.getApplicationContext())
                    .registerActivityLifecycleCallbacks(new DispatcherActivityCallback());
        }
    
        @SuppressWarnings("WeakerAccess")
        @VisibleForTesting
        static class DispatcherActivityCallback extends EmptyActivityLifecycleCallbacks {
            private final FragmentCallback mFragmentCallback;
    
            DispatcherActivityCallback() {
                mFragmentCallback = new FragmentCallback();
            }
    
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                if (activity instanceof FragmentActivity) {
                    ((FragmentActivity) activity).getSupportFragmentManager()
                            .registerFragmentLifecycleCallbacks(mFragmentCallback, true);
                }
                ReportFragment.injectIfNeededIn(activity);
            }
    

    init初始化之后,在DispatcherActivityCallback中ReportFragment.injectIfNeededIn(activity);将activity注入到了ReportFragment,接着看ReportFragment

    @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
    public class ReportFragment extends Fragment {
        private static final String REPORT_FRAGMENT_TAG = "android.arch.lifecycle"
                + ".LifecycleDispatcher.report_fragment_tag";
    
        public static void injectIfNeededIn(Activity activity) {
            // ProcessLifecycleOwner should always correctly work and some activities may not extend
            // FragmentActivity from support lib, so we use framework fragments for activities
            android.app.FragmentManager manager = activity.getFragmentManager();
            if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
                manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
                // Hopefully, we are the first to make a transaction.
                manager.executePendingTransactions();
            }
        }
    
        static ReportFragment get(Activity activity) {
            return (ReportFragment) activity.getFragmentManager().findFragmentByTag(
                    REPORT_FRAGMENT_TAG);
        }
    
        private ActivityInitializationListener mProcessListener;
    
        private void dispatchCreate(ActivityInitializationListener listener) {
            if (listener != null) {
                listener.onCreate();
            }
        }
    
        private void dispatchStart(ActivityInitializationListener listener) {
            if (listener != null) {
                listener.onStart();
            }
        }
    
        private void dispatchResume(ActivityInitializationListener listener) {
            if (listener != null) {
                listener.onResume();
            }
        }
    
        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
            dispatchCreate(mProcessListener);
            dispatch(Lifecycle.Event.ON_CREATE);
        }
    
        @Override
        public void onStart() {
            super.onStart();
            dispatchStart(mProcessListener);
            dispatch(Lifecycle.Event.ON_START);
        }
    
        @Override
        public void onResume() {
            super.onResume();
            dispatchResume(mProcessListener);
            dispatch(Lifecycle.Event.ON_RESUME);
        }
    
        @Override
        public void onPause() {
            super.onPause();
            dispatch(Lifecycle.Event.ON_PAUSE);
        }
    
        @Override
        public void onStop() {
            super.onStop();
            dispatch(Lifecycle.Event.ON_STOP);
        }
    
        @Override
        public void onDestroy() {
            super.onDestroy();
            dispatch(Lifecycle.Event.ON_DESTROY);
            // just want to be sure that we won't leak reference to an activity
            mProcessListener = null;
        }
    
        private void dispatch(Lifecycle.Event event) {
            Activity activity = getActivity();
            if (activity instanceof LifecycleRegistryOwner) {
                ((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
                return;
            }
    
            if (activity instanceof LifecycleOwner) {
                Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
                if (lifecycle instanceof LifecycleRegistry) {
                    ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
                }
            }
        }
    
        void setProcessListener(ActivityInitializationListener processListener) {
            mProcessListener = processListener;
        }
    
        interface ActivityInitializationListener {
            void onCreate();
    
            void onStart();
    
            void onResume();
        }
    }
    

    通过injectIfNeededIn方法创建了ReportFragment,通过管理ReportFragment的声明周期,dispatch(Lifecycle.Event.ON_PAUSE);将声明周期枚举进行分发

    private void dispatch(Lifecycle.Event event) {
            Activity activity = getActivity();
            if (activity instanceof LifecycleRegistryOwner) {
                ((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
                return;
            }
    
            if (activity instanceof LifecycleOwner) {
                Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
                if (lifecycle instanceof LifecycleRegistry) {
                    ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
                }
            }
        }
    

    最后event赋值给了LifecycleRegistry中mState,并通过getCurrentState获取
    则Lifecycle通过getCurrentState()可以取到当前activity的声明周期了

    看看为什么不会导致内存泄漏

     @MainThread
        public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<T> observer) {
            if (owner.getLifecycle().getCurrentState() == DESTROYED) {
                // ignore
                return;
            }
            LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer);
            ObserverWrapper existing = mObservers.putIfAbsent(observer, wrapper);
            if (existing != null && !existing.isAttachedTo(owner)) {
                throw new IllegalArgumentException("Cannot add the same observer"
                        + " with different lifecycles");
            }
            if (existing != null) {
                return;
            }
            owner.getLifecycle().addObserver(wrapper);
        }
    
    @Override
            public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
                if (mOwner.getLifecycle().getCurrentState() == DESTROYED) {
                    removeObserver(mObserver);
                    return;
                }
                activeStateChanged(shouldBeActive());
            }
    

    当执行observe和onStateChanged都有判断当前activity是否destroyed,由此可见,activity销毁了,并不会执行数据更新,自然不会有内存泄漏

    三.viewModel如何实现数据共享

    主要是同一个HolderFragment,导致有同一个ViewModelStore,同一个ViewModelStore存的key是同一个,所以get获取到的viewModel是同一个,数据自然能共享,我们来一步步解析

    class ViewModelDelegate<out T : BaseViewModel>(private val clazz: KClass<T>, private val fromActivity: Boolean) {
    
        private var viewModel: T? = null
    
        operator fun getValue(thisRef: BaseActivity, property: KProperty<*>) = buildViewModel(activity = thisRef)
    
        operator fun getValue(thisRef: BaseFragment, property: KProperty<*>) = if (fromActivity)
            buildViewModel(activity = thisRef.activity as? BaseActivity
                    ?: throw IllegalStateException("Activity must be as BaseActivity"))
        else buildViewModel(fragment = thisRef)
    
        private fun buildViewModel(activity: BaseActivity? = null, fragment: BaseFragment? = null): T {
            if (viewModel != null) return viewModel!!
    
            activity?.let {
                viewModel = ViewModelProviders.of(it).get(clazz.java)
            } ?: fragment?.let {
                viewModel = ViewModelProviders.of(it).get(clazz.java)
            } ?: throw IllegalStateException("Activity and Fragment null! =(")
    
            return viewModel!!
        }
    }
    
    fun <T : BaseViewModel> BaseActivity.viewModelDelegate(clazz: KClass<T>) = ViewModelDelegate(clazz, true)
    
    // fromActivity默认为true,viewModel生命周期默认跟activity相同 by aaron 2018/7/24
    fun <T : BaseViewModel> BaseFragment.viewModelDelegate(clazz: KClass<T>, fromActivity: Boolean = true) = ViewModelDelegate(clazz, fromActivity)
    

    这是通过代理生成的viewModel,我们来看ViewModelProviders.of(it).get(clazz.java)里面做了一些什么

    @NonNull
        @MainThread
        public static ViewModelProvider of(@NonNull FragmentActivity activity) {
            return of(activity, null);
        }
    
     @NonNull
        @MainThread
        public static ViewModelProvider of(@NonNull FragmentActivity activity,
                @Nullable Factory factory) {
            Application application = checkApplication(activity);
            if (factory == null) {
                factory = ViewModelProvider.AndroidViewModelFactory.getInstance(application);
            }
            return new ViewModelProvider(ViewModelStores.of(activity), factory);
        }
    

    如上,首先默认传入Factory为null,会通过ViewModelProvider.AndroidViewModelFactory.getInstance(application);去获取单例的factory,接着看ViewModelStores.of(activity)

     @NonNull
        @MainThread
        public static ViewModelStore of(@NonNull FragmentActivity activity) {
            if (activity instanceof ViewModelStoreOwner) {
                return ((ViewModelStoreOwner) activity).getViewModelStore();
            }
            return holderFragmentFor(activity).getViewModelStore();
        }
    

    if (activity instanceof ViewModelStoreOwner)并不会执行,那么走holderFragmentFor(activity).getViewModelStore(); holderFragmentFor(activity)如下,是获取HolderFragment

    @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
        public static HolderFragment holderFragmentFor(FragmentActivity activity) {
            return sHolderFragmentManager.holderFragmentFor(activity);
        }
    

    sHolderFragmentManager是静态内部类HolderFragmentManager,而HolderFragmentManager是饿汉式创建的单例

    private static final HolderFragmentManager sHolderFragmentManager = new HolderFragmentManager();
    

    接着往下看

    HolderFragment holderFragmentFor(FragmentActivity activity) {
                FragmentManager fm = activity.getSupportFragmentManager();
                HolderFragment holder = findHolderFragment(fm);
                if (holder != null) {
                    return holder;
                }
                holder = mNotCommittedActivityHolders.get(activity);
                if (holder != null) {
                    return holder;
                }
    
                if (!mActivityCallbacksIsAdded) {
                    mActivityCallbacksIsAdded = true;
                    activity.getApplication().registerActivityLifecycleCallbacks(mActivityCallbacks);
                }
                holder = createHolderFragment(fm);
                mNotCommittedActivityHolders.put(activity, holder);
                return holder;
            }
    

    首先是findHolderFragment(fm),在activity的supportFragmentManager中查找,如下,通过同一个tag获取到HolderFragment,
    如果HolderFragment不为空直接返回,如果为空通过mNotCommittedActivityHolders.get(activity),
    如果HolderFragment为空,通过createHolderFragment()创建 ,tag为HOLDER_TAG,并方法mNotCommittedActivityHolders的map中
    由此可见findHolderFragment,mNotCommittedActivityHolders.get(activity),在多个activity中获取的HolderFragment可能是同一个

      private static HolderFragment createHolderFragment(FragmentManager fragmentManager) {
                HolderFragment holder = new HolderFragment();
                fragmentManager.beginTransaction().add(holder, HOLDER_TAG).commitAllowingStateLoss();
                return holder;
            }
    
    private static HolderFragment findHolderFragment(FragmentManager manager) {
                if (manager.isDestroyed()) {
                    throw new IllegalStateException("Can't access ViewModels from onDestroy");
                }
    
                Fragment fragmentByTag = manager.findFragmentByTag(HOLDER_TAG);
                if (fragmentByTag != null && !(fragmentByTag instanceof HolderFragment)) {
                    throw new IllegalStateException("Unexpected "
                            + "fragment instance was returned by HOLDER_TAG");
                }
                return (HolderFragment) fragmentByTag;
            }
    

    再回到上面holderFragmentFor(activity).getViewModelStore(),看getViewModelStore()方法

    private ViewModelStore mViewModelStore = new ViewModelStore();
    
    @NonNull
        @Override
        public ViewModelStore getViewModelStore() {
            return mViewModelStore;
        }
    

    在HolderFragment中创建的ViewModelStore,则为同一个ViewModelStore

    最后再看ViewModelProviders.of(it).get(clazz.java)中get方法

    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) {
            ViewModel viewModel = mViewModelStore.get(key);
    
            if (modelClass.isInstance(viewModel)) {
                //noinspection unchecked
                return (T) viewModel;
            } else {
                //noinspection StatementWithEmptyBody
                if (viewModel != null) {
                    // TODO: log a warning.
                }
            }
    
            viewModel = mFactory.create(modelClass);
            mViewModelStore.put(key, viewModel);
            //noinspection unchecked
            return (T) viewModel;
        }
    

    主要看ViewModel viewModel = mViewModelStore.get(key);viewmodel的获取是通过mViewModelStore取到

     @NonNull
        @MainThread
        public static ViewModelProvider of(@NonNull FragmentActivity activity,
                @Nullable Factory factory) {
            Application application = checkApplication(activity);
            if (factory == null) {
                factory = ViewModelProvider.AndroidViewModelFactory.getInstance(application);
            }
            return new ViewModelProvider(ViewModelStores.of(activity), factory);
        }
    
     public ViewModelProvider(@NonNull ViewModelStore store, @NonNull Factory factory) {
            mFactory = factory;
            this.mViewModelStore = store;
        }
    

    首先是我们从mViewModelStore取出我们想要的ViewModel.
    有的话就返回
    而mViewModelStore是通过ViewModelStores.of(activity)取到的当前activity中的同一个mViewModelStore通过key,则获取了我们想要的viewModel

    没有的话就利用工厂模式反射生产我们所要的ViewModel对象,同时把我们的ViewModel对象放入mViewModelStore。同时返回我们的ViewModel.

    由此可见,同一个activity中获取的对应的viewmodel是同一个,那么fragment中viewmodel数据自然能共享

    四.viewModel实现数据保存

    主要是横屏竖屏下,activity会重启,数据会重新获取,使用viewModel时,viewModel是存在HoldFragment中的ViewModelStore中

    public HolderFragment() {
            setRetainInstance(true);
        }
    

    可见HolderFragment调用setsetRetainInstance(true),使得HolderFragment在FragmentMannager调用FindFragmentBytag,找到的是同一个HolderFragment对象(无论Activity是否重绘),这也保证了HolderFragment中的ViewModelStore(存放我们ViewModel的地方)不被销毁,然后我们取出我们所要的ViewModel,进行数据读取

    相关文章

      网友评论

        本文标题:Android AAC架构解析

        本文链接:https://www.haomeiwen.com/subject/bpudaftx.html