关于android:Android-AAC架构实践

53次阅读

共计 20374 个字符,预计需要花费 51 分钟才能阅读完成。

  • LiveData 如何实现数据更新
  • 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 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 根底系列教程:
Android 根底课程 U - 小结_哔哩哔哩_bilibili
Android 根底课程 UI- 布局_哔哩哔哩_bilibili
Android 根底课程 UI- 控件_哔哩哔哩_bilibili
Android 根底课程 UI- 动画_哔哩哔哩_bilibili
Android 根底课程 -activity 的应用_哔哩哔哩_bilibili
Android 根底课程 -Fragment 应用办法_哔哩哔哩_bilibili
Android 根底课程 - 热修复 / 热更新技术原理_哔哩哔哩_bilibili

本文转自 https://juejin.cn/post/7041098418499878949,如有侵权,请分割删除。

正文完
 0