Android Architecture Components原理浅析

前言:

前文已经讲述了Android架构化组件的一些基本用法和整体使用场景。但是因为笔者在学习和研究这些组件的时候本身也是带有一些疑惑和问题的,考虑到可能也会有人有相同的疑惑,所以将此过程中发现疑惑和解决问题的思路和过程记录下来,供有需要的同学查阅。

1、ViewModel:

不知道大家在学习和使用ViewModel的时候,是否有这个疑问。一般情况下的Activity销毁和横竖屏切换时的Activity销毁,Activity都是已经被销毁掉了(横竖屏切换时Activity的实例对象不是同一个对象),那为什么前者的ViewModel会被销毁掉,而后者却没有呢?关于这个问题,笔者一直带有很大的疑问,但是官方文档只是说在横竖屏切换时ViewModel不销毁,而且一直拿Activity生命周期Scope说事儿,导致笔者对此产生了更多的疑惑,好奇心驱使我查看了相关源码,终于明白了这部分的内部实现。

ChronometerViewModel chronometerViewModel
        = ViewModelProviders.of(this).get(ChronometerViewModel.class);
public static ViewModelProvider of(@NonNull FragmentActivity activity) {
    initializeFactoryIfNeeded(checkApplication(activity));
    return new ViewModelProvider(ViewModelStores.of(activity), sDefaultFactory);
}
public ViewModelProvider(@NonNull ViewModelStore store, @NonNull Factory factory) {
    mFactory = factory;
    this.mViewModelStore = store;
}
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);
}
public class ViewModelStore {

    private final HashMap<String, ViewModel> mMap = new HashMap<>();

    final void put(String key, ViewModel viewModel) {
        ViewModel oldViewModel = mMap.get(key);
        if (oldViewModel != null) {
            oldViewModel.onCleared();
        }
        mMap.put(key, viewModel);
    }

    final ViewModel get(String key) {
        return mMap.get(key);
    }

    /**
     *  Clears internal storage and notifies ViewModels that they are no longer used.
     */
    public final void clear() {
        for (ViewModel vm : mMap.values()) {
            vm.onCleared();
        }
        mMap.clear();
    }
}

通过上述ViewModel的生成和调用流程,我们看出ViewModel其实是储存在ViewModelStore 中的,而ViewModelStore 里主要是放了一个map,key就是这个Activity的名字+“android.arch.lifecycle.ViewModelProvider.DefaultKey”,而Value就是ViewModel。
那么此时我们就清楚ViewModel是如何存放的了,按照官方文档的说法,Activity销毁时,会将对应的ViewModel的也销毁,那么销毁的方式也就是调用ViewModelStore .clear()方法。可是这些依然没办法解决我们的疑惑,为啥横竖屏切换时,Activty也销毁了,ViewModelStore .clear()方法却没有调用呢?

好的,知道ViewModel的销毁是通过ViewModelStore .clear()来实现的,我们就看下这个方法是在哪里调用的。然后我们就看到了如下:
有个叫HolderFragment的类调用了这个方法:

public class HolderFragment extends Fragment {
    private static final String LOG_TAG = "ViewModelStores";
    private static final HolderFragmentManager sHolderFragmentManager = new HolderFragmentManager();
    /**
     * @hide
     */
    @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
    public static final String HOLDER_TAG =
            "android.arch.lifecycle.state.StateProviderHolderFragment";
    private ViewModelStore mViewModelStore = new ViewModelStore();
    public HolderFragment() {
        setRetainInstance(true);
    }
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sHolderFragmentManager.holderFragmentCreated(this);
    }
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        mViewModelStore.clear();
    }
    public ViewModelStore getViewModelStore() {
        return mViewModelStore;
    }
  ...
}

我们看到HolderFragment中持有了mViewModelStore 这个对象,而且在它的onDestroy方法中调用了mViewModelStore.clear();方法。看到这里,就有些疑问,这个HolderFragment是哪里来的?

public static ViewModelProvider of(@NonNull FragmentActivity activity) {
    initializeFactoryIfNeeded(checkApplication(activity));
    return new ViewModelProvider(ViewModelStores.of(activity), sDefaultFactory);
}

根据这段代码,可以看出,ViewModelStore是从ViewModelStores.of(activity)这里拿到的。接下来我们看一下
ViewModelStores的代码:

public class ViewModelStores {

    private ViewModelStores() {
    }

    /**
     * Returns the {@link ViewModelStore} of the given activity.
     *
     * @param activity an activity whose {@code ViewModelStore} is requested
     * @return a {@code ViewModelStore}
     */
    @MainThread
    public static ViewModelStore of(@NonNull FragmentActivity activity) {
        return holderFragmentFor(activity).getViewModelStore();
    }

    /**
     * Returns the {@link ViewModelStore} of the given fragment.
     *
     * @param fragment a fragment whose {@code ViewModelStore} is requested
     * @return a {@code ViewModelStore}
     */
    @MainThread
    public static ViewModelStore of(@NonNull Fragment fragment) {
        return holderFragmentFor(fragment).getViewModelStore();
    }
}

我们看到ViewModelStore实际上是从holderFragmentFor(activity).getViewModelStore();中拿到的,而holderFragmentFor(activity)其实就是HodlerFragment!

此时再思考之前的问题,mViewModelStore.clear();只在HodlerFragment的onDestroy方法中有调用,那么能解释上述问题的唯一可能就是,在横竖屏切换时,HolderFragment的onDestroy方法并未调用!而普通的Activity销毁时,HolderFragment的onDestroy是会调用的。

带着这个问题,继续看HolderFragment,然后就看到了它的构造方法:

public HolderFragment() {
    setRetainInstance(true);
}

点进去这个方法,我们看到 setRetainInstance(true);是Fragment中的一个方法:

Frargment:

/**
     * Control whether a fragment instance is retained across Activity
     * re-creation (such as from a configuration change).  This can only
     * be used with fragments not in the back stack.  If set, the fragment
     * lifecycle will be slightly different when an activity is recreated:
     * <ul>
     * <li> {@link #onDestroy()} will not be called (but {@link #onDetach()} still
     * will be, because the fragment is being detached from its current activity).
     * <li> {@link #onCreate(Bundle)} will not be called since the fragment
     * is not being re-created.
     * <li> {@link #onAttach(Activity)} and {@link #onActivityCreated(Bundle)} <b>will</b>
     * still be called.
     * </ul>
     */
    public void setRetainInstance(boolean retain) {
        mRetainInstance = retain;
    }

    final public boolean getRetainInstance() {
        return mRetainInstance;
    }

从这个方法的注释中,我们看到,mRetainInstance 被设置为true时,在Activity被重新创建时(比如横竖屏切换),HolderFragment的OnDestroy方法并不会被调用,而是只调用onDetach方法。而且在Activity 重建时,
HolderFragment的onCreate方法也不会被调用,而是会调用onAttach和onActivityCreated方法。(也比较好理解,没有destroy,只是onDetch而已,自然不需要再重新调用onCreate方法)。

至此,我们的疑惑也就迎刃而解了,横竖屏切换时,HolderFragment的onDestroy方法不会被调用,ViewModelStore不会clear,那么ViewModel自然存在,并可供下个Activity实例使用。

好奇的我们再看下Fragment中mRetainInstance是怎么用的。
然后我们看到FragmentManagerImpl的一个方法中的调用:

void saveNonConfig() {
        ArrayList<Fragment> fragments = null;
        ArrayList<FragmentManagerNonConfig> childFragments = null;
        if (mActive != null) {
            for (int i=0; i<mActive.size(); i++) {
                Fragment f = mActive.valueAt(i);
                if (f != null) {
                    if (f.mRetainInstance) {
                        if (fragments == null) {
                            fragments = new ArrayList<Fragment>();
                        }
                        fragments.add(f);
                        f.mTargetIndex = f.mTarget != null ? f.mTarget.mIndex : -1;
                        if (DEBUG) Log.v(TAG, "retainNonConfig: keeping retained " + f);
                    }
                    FragmentManagerNonConfig child;
                    if (f.mChildFragmentManager != null) {
                        f.mChildFragmentManager.saveNonConfig();
                        child = f.mChildFragmentManager.mSavedNonConfig;
                    } else {
                        // f.mChildNonConfig may be not null, when the parent fragment is
                        // in the backstack.
                        child = f.mChildNonConfig;
                    }

                    if (childFragments == null && child != null) {
                        childFragments = new ArrayList<>(mActive.size());
                        for (int j = 0; j < i; j++) {
                            childFragments.add(null);
                        }
                    }

                    if (childFragments != null) {
                        childFragments.add(child);
                    }
                }
            }
        }
        if (fragments == null && childFragments == null) {
            mSavedNonConfig = null;
        } else {
            mSavedNonConfig = new FragmentManagerNonConfig(fragments, childFragments);
        }
    }
if (f.mRetainInstance) {
    if (fragments == null) {
        fragments = new ArrayList<Fragment>();
    }
    fragments.add(f);
    f.mTargetIndex = f.mTarget != null ? f.mTarget.mIndex : -1;
    if (DEBUG) Log.v(TAG, "retainNonConfig: keeping retained " + f);
}

通过上述代码可以看出,保存状态时,如果mRetainInstance为true,会将fragment加入到集合中,而不是销毁掉,在需要的时候,再从List中拿出来attach Activity。

而其实笔者关于HolderFragment还是有些好奇,HolderFragment到底是干啥用的呢?但是因为本文的主题,不想做过多的扩展,根据HolderFragment源码:

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;
}

HolderFragment是会被默认加入到FragementActivity中的,而普通的Activity是不支持ViewModel的,FragementActivity支持ViewModel。那么我们大概可以了解HolderFragment的设计目的中有一项就是解决VIewModel在横竖屏切换下不销毁的。更多的就不做扩展了,感兴趣的小伙伴可以去看源码。

2、LiveData:

通知更新有两种情况,一种是数据变化,另一种是Observer的LifecycleOwner的状态变化(比如从不可更新状态变为可更新状态)


LiveData1.png
LiveData2.png

LiveData3.png
LiveData4.png
LiveData5.png
LiveData6.png

根据上述源码可知,LiveData只会在Observer的LifecycleOwner的生命周期处于>STARTED的状态的时候才会通知更新。

LiveData7.png
LiveData8.png
LiveData9.png

postValue是通过开启异步线程,然后通过Runnable中调用setValue来实现异步线程数据变化时,通知主线程更新UI。注意setValue方法中的mVersion,该字段主要用于避免重复回调,LiveData的mVersion字段会和Oberser的lastVersion字段进行比较来确认此次数据变化是否已经回调过了。从代码中可以看出,setValu方法每执行一次,mVersion都会加1。

可能有些人会比较好奇,上面的LifeCycleBoundObserver的onStateChanged方法是在哪里触发调用的呢?

LiveData10.png
LiveData11.png

可以看到在LifeCycleRegistry的addObserver方法中,会一直判断当前Observer的LifeCycleOwner的生命周期是否发生变化,一旦变化就通知在管理列表里的Observer,在dispatchEvent方法中调用通知方法(mLifeCycleObserver.onStateChanged()方法)。

3、LifecycleObserver:

这里我们主要是看被注解的方法是如何在达到生命周期的状态时,被调用的。
我们看上图中的ObserverWithState方法,看到
mLifecycleObserver = Lifecycling.getCallback(observer);
点进去Lifecycling类可以看到:

LivecycleObserver1.png
LifecycleObsever2.png

在生命周期状态变化时,会调用CallbackInfo.invokeCallbacks方法,而CallbackInfo 是ClassesInfoCache的内部类。


LifecycleObserver4.png
private CallbackInfo createInfo(Class klass, @Nullable Method[] declaredMethods) {
        Class superclass = klass.getSuperclass();
        Map<MethodReference, Lifecycle.Event> handlerToEvent = new HashMap<>();
        if (superclass != null) {
            CallbackInfo superInfo = getInfo(superclass);
            if (superInfo != null) {
                handlerToEvent.putAll(superInfo.mHandlerToEvent);
            }
        }

        Class[] interfaces = klass.getInterfaces();
        for (Class intrfc : interfaces) {
            for (Map.Entry<MethodReference, Lifecycle.Event> entry : getInfo(
                    intrfc).mHandlerToEvent.entrySet()) {
                verifyAndPutHandler(handlerToEvent, entry.getKey(), entry.getValue(), klass);
            }
        }

        Method[] methods = declaredMethods != null ? declaredMethods : getDeclaredMethods(klass);
        boolean hasLifecycleMethods = false;
        for (Method method : methods) {
            OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);
            if (annotation == null) {
                continue;
            }
            hasLifecycleMethods = true;
            Class<?>[] params = method.getParameterTypes();
            int callType = CALL_TYPE_NO_ARG;
            if (params.length > 0) {
                callType = CALL_TYPE_PROVIDER;
                if (!params[0].isAssignableFrom(LifecycleOwner.class)) {
                    throw new IllegalArgumentException(
                            "invalid parameter type. Must be one and instanceof LifecycleOwner");
                }
            }
            Lifecycle.Event event = annotation.value();

            if (params.length > 1) {
                callType = CALL_TYPE_PROVIDER_WITH_EVENT;
                if (!params[1].isAssignableFrom(Lifecycle.Event.class)) {
                    throw new IllegalArgumentException(
                            "invalid parameter type. second arg must be an event");
                }
                if (event != Lifecycle.Event.ON_ANY) {
                    throw new IllegalArgumentException(
                            "Second arg is supported only for ON_ANY value");
                }
            }
            if (params.length > 2) {
                throw new IllegalArgumentException("cannot have more than 2 params");
            }
            MethodReference methodReference = new MethodReference(callType, method);
            verifyAndPutHandler(handlerToEvent, methodReference, event, klass);
        }
        CallbackInfo info = new CallbackInfo(handlerToEvent);
        mCallbackMap.put(klass, info);
        mHasLifecycleMethods.put(klass, hasLifecycleMethods);
        return info;
    }
static class CallbackInfo {
        final Map<Lifecycle.Event, List<MethodReference>> mEventToHandlers;
        final Map<MethodReference, Lifecycle.Event> mHandlerToEvent;

        CallbackInfo(Map<MethodReference, Lifecycle.Event> handlerToEvent) {
            mHandlerToEvent = handlerToEvent;
            mEventToHandlers = new HashMap<>();
            for (Map.Entry<MethodReference, Lifecycle.Event> entry : handlerToEvent.entrySet()) {
                Lifecycle.Event event = entry.getValue();
                List<MethodReference> methodReferences = mEventToHandlers.get(event);
                if (methodReferences == null) {
                    methodReferences = new ArrayList<>();
                    mEventToHandlers.put(event, methodReferences);
                }
                methodReferences.add(entry.getKey());
            }
        }

        @SuppressWarnings("ConstantConditions")
        void invokeCallbacks(LifecycleOwner source, Lifecycle.Event event, Object target) {
            invokeMethodsForEvent(mEventToHandlers.get(event), source, event, target);
            invokeMethodsForEvent(mEventToHandlers.get(Lifecycle.Event.ON_ANY), source, event,
                    target);
        }

        private static void invokeMethodsForEvent(List<MethodReference> handlers,
                LifecycleOwner source, Lifecycle.Event event, Object mWrapped) {
            if (handlers != null) {
                for (int i = handlers.size() - 1; i >= 0; i--) {
                    handlers.get(i).invokeCallback(source, event, mWrapped);
                }
            }
        }
    }
void invokeCallback(LifecycleOwner source, Lifecycle.Event event, Object target) {
            //noinspection TryWithIdenticalCatches
            try {
                switch (mCallType) {
                    case CALL_TYPE_NO_ARG:
                        mMethod.invoke(target);
                        break;
                    case CALL_TYPE_PROVIDER:
                        mMethod.invoke(target, source);
                        break;
                    case CALL_TYPE_PROVIDER_WITH_EVENT:
                        mMethod.invoke(target, source, event);
                        break;
                }
            } catch (InvocationTargetException e) {
                throw new RuntimeException("Failed to call observer method", e.getCause());
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }

3、Room:

BookDao_impl:

  @Override
  public LiveData<List<Book>> findBooksBorrowedByNameAfter(String userName, Date after) {
    final String _sql = "SELECT * FROM Book INNER JOIN Loan ON Loan.book_id = Book.id INNER JOIN User on User.id = Loan.user_id WHERE User.name LIKE ? AND Loan.endTime > ? ";
    final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire(_sql, 2);
    int _argIndex = 1;
    if (userName == null) {
      _statement.bindNull(_argIndex);
    } else {
      _statement.bindString(_argIndex, userName);
    }
    _argIndex = 2;
    final Long _tmp;
    _tmp = DateConverter.toTimestamp(after);
    if (_tmp == null) {
      _statement.bindNull(_argIndex);
    } else {
      _statement.bindLong(_argIndex, _tmp);
    }
    return new ComputableLiveData<List<Book>>() {
      private Observer _observer;

      @Override
      protected List<Book> compute() {
        if (_observer == null) {
          _observer = new Observer("Book","Loan","User") {
            @Override
            public void onInvalidated(@NonNull Set<String> tables) {
              invalidate();
            }
          };
          __db.getInvalidationTracker().addWeakObserver(_observer);
        }
        final Cursor _cursor = __db.query(_statement);
        try {
          final int _cursorIndexOfId = _cursor.getColumnIndexOrThrow("id");
          final int _cursorIndexOfTitle = _cursor.getColumnIndexOrThrow("title");
          final int _cursorIndexOfId_1 = _cursor.getColumnIndexOrThrow("id");
          final int _cursorIndexOfId_2 = _cursor.getColumnIndexOrThrow("id");
          final List<Book> _result = new ArrayList<Book>(_cursor.getCount());
          while(_cursor.moveToNext()) {
            final Book _item;
            _item = new Book();
            _item.id = _cursor.getString(_cursorIndexOfId);
            _item.title = _cursor.getString(_cursorIndexOfTitle);
            _item.id = _cursor.getString(_cursorIndexOfId_1);
            _item.id = _cursor.getString(_cursorIndexOfId_2);
            _result.add(_item);
          }
          return _result;
        } finally {
          _cursor.close();
        }
      }

      @Override
      protected void finalize() {
        _statement.release();
      }
    }.getLiveData();
  }
/**
     * Creates a computable live data which is computed when there are active observers.
     * <p>
     * It can also be invalidated via {@link #invalidate()} which will result in a call to
     * {@link #compute()} if there are active observers (or when they start observing)
     */
    @SuppressWarnings("WeakerAccess")
    public ComputableLiveData() {
        mLiveData = new LiveData<T>() {
            @Override
            protected void onActive() {
                // TODO if we make this class public, we should accept an executor
                ArchTaskExecutor.getInstance().executeOnDiskIO(mRefreshRunnable);
            }
        };
    }
@Query("SELECT * FROM Book " +
            "INNER JOIN Loan ON Loan.book_id = Book.id " +
            "INNER JOIN User on User.id = Loan.user_id " +
            "WHERE User.name LIKE :userName " +
            "AND Loan.endTime > :after "
    )
    LiveData<List<Book>> findBooksBorrowedByNameAfter(String userName, Date after);

    @Query("SELECT * FROM Book " +
            "INNER JOIN Loan ON Loan.book_id = Book.id " +
            "INNER JOIN User on User.id = Loan.user_id " +
            "WHERE User.name LIKE :userName"
    )
    List<Book> findBooksBorrowedByNameSync(String userName);

可以看出在BookDao类中,从数据库中读取book数据的操作,第一个方法是异步的,第二个方法则是同步操作,需要自己开线程进行异步操作,再回调给主线程。

推荐阅读更多精彩内容