Android MVVM 解读 3. Android MVVM

作者: yqpan1991 | 来源:发表于2020-02-21 01:20 被阅读0次

    Android MVVM 解读 3. Android MVVM 介绍(1)

    包含的信息

    1. Android MVVM 架构设计
    2. 源码解析 - Lifecycle部分

    1. 架构设计

    1.1 Guide to app architechture

    在上面的链接, 查看安卓推荐的架构设计以及包含的简单的Demo介绍

    在这里插入图片描述

    1.2. 案例GithubBrowserSample

    在了解了这个复杂的案例后, 我们然后总结下

    1.3 总结

    1.3.1 关系对应

    在上篇Android MVVM 解读 2.MVC, MVP, MVVM中,我们介绍了MVVM的框架结构,我们一一对应Android上的实现

    MVVM
    1. MVVM View --> Fragment,Activity, Customed View
    2. MVVM DataBinding --> Android DataBinding Library
    3. MVVM ViewModel --> Android ViewModel
    4. MVVM Model --> Repository(Model + Remote Data Source)
    5. MVVM observable Field --> LiveData(LiveData + LifeCycle + Observer)

    1.3.2 开发的Step

    1. 定义POJO
    2. 定义POJO相关的LiveData
    3. 定义Repository(Model + Remote Data Source)
    4. 定义ViewModel
    5. 定义View
    6. 自动生成DataBinding

    既然MVVM的框架的类,在Android中都已经体现,并且知道了开发的步骤,接下来便可以查看安卓的具体的实现, 我们按照开发的Step来找

    2. 源码解析

    2.1 POJO

    此步骤忽略,一般为简单的数据对象,eg.Person, Cat 等等

    2.2 LifeCycle

    在开始分析源码前,先查看下google的这篇简介和案例的文章 Handling Lifecycles with Lifecycle-Aware Components

    2.2.1 理解

    官方解释:

    1. LifeCycle出现的目的是: 为了方便组件A监听有生命周期的组件B,在B的生命周期变化时,A需要作出相应的改变
    2. 通常的做法是, 直接将组件B的生命周期,直接跟Activity或者Fragment结合,但是这种模式,会导致代码不好管理.生命周期组件,将这部分依赖具体的组件的生命周期的部分中剥离, 并且由自身控制

    个人理解

    1. 之前在开发组件A时,我们监听具体的Activity或者fragment的生命周期时,直接在activity或者fragment中的onResume,onCreate等具体的生命周期中,做开发,一旦需要移动activity或者fragment,或者代码剥离时,发现这块更改时比较困难, 那么是否有方法,可以不关注依赖的组件是那种类型呢? 无论是activity,fragment,service或者是application,只要你遵守生命周期相关的状态,开发的逻辑便可以是不便的.
      答案是可以的,任何的A和B直接依赖的方式,便可以通过增加一个C,作为桥梁,解决这些问题.LifeCycle的组件便是作为C的存在.

    2. LifeCycle提供现有的机制, 将Activity和Fragment, Service, Application的生命周期抽象化,总结为几种状态, INITIALIZED, DESTROYED, CREATED, STARTED, RESUMED

    Android MVVM State
    1. LifeCycle将Activity,Fragment,Service,Application作为生命周期的提供者, 而具体的组件A作为消费者,LifeCycle提供注册器(LifecycleRegistry) ,将A注册到注册器中,便可以方便的在状态变化时,做相关的操作

    案例

    2.2.2 类图

    android-mvvm-lifecycle

    说明
    通知机制中, 可以重点看下支持的通知方式

    1. 注解的方式
    2. 普通接口的使用方式

    2.2.2.1 通知方式的实现

    1. 类ObserverWithState

    针对注解的方式, 使用方便,而且不需要更改现有的代码,但是性能低下,可以从LifecycleRegistry.ObserverWithState的构造作为入口查看, 首先获取到通知的方式, mLifecycleObserver, 在状态变化时,通过mLifecycleObserver.onStateChanged(owner, event) 通知变更

       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)的实现

    2. Lifecycling.getCallback(observer)

    @NonNull
    static GenericLifecycleObserver getCallback(Object object) {
        if (object instanceof FullLifecycleObserver) {
            return new FullLifecycleObserverAdapter((FullLifecycleObserver) object);
        }
    
        if (object instanceof GenericLifecycleObserver) {
            return (GenericLifecycleObserver) object;
        }
    
        final Class<?> klass = object.getClass();
        int type = getObserverConstructorType(klass);
        if (type == GENERATED_CALLBACK) {
            List<Constructor<? extends GeneratedAdapter>> constructors =
                    sClassToAdapters.get(klass);
            if (constructors.size() == 1) {
                GeneratedAdapter generatedAdapter = createGeneratedAdapter(
                        constructors.get(0), object);
                return new SingleGeneratedAdapterObserver(generatedAdapter);
            }
            GeneratedAdapter[] adapters = new GeneratedAdapter[constructors.size()];
            for (int i = 0; i < constructors.size(); i++) {
                adapters[i] = createGeneratedAdapter(constructors.get(i), object);
            }
            return new CompositeGeneratedAdaptersObserver(adapters);
        }
        return new ReflectiveGenericLifecycleObserver(object);
    }
    

    重点是两个: FullLifecycleObserver和ReflectiveGenericLifecycleObserver

    3. FullLifecycleObserverAdapter和FullLifecycleObserver

    class FullLifecycleObserverAdapter implements GenericLifecycleObserver {
    
        private final FullLifecycleObserver mObserver;
    
        FullLifecycleObserverAdapter(FullLifecycleObserver observer) {
            mObserver = observer;
        }
    
        @Override
        public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
            switch (event) {
                case ON_CREATE:
                    mObserver.onCreate(source);
                    break;
                case ON_START:
                    mObserver.onStart(source);
                    break;
                case ON_RESUME:
                    mObserver.onResume(source);
                    break;
                case ON_PAUSE:
                    mObserver.onPause(source);
                    break;
                case ON_STOP:
                    mObserver.onStop(source);
                    break;
                case ON_DESTROY:
                    mObserver.onDestroy(source);
                    break;
                case ON_ANY:
                    throw new IllegalArgumentException("ON_ANY must not been send by anybody");
            }
        }
    }
    
    
    interface FullLifecycleObserver extends LifecycleObserver {
    
        void onCreate(LifecycleOwner owner);
    
        void onStart(LifecycleOwner owner);
    
        void onResume(LifecycleOwner owner);
    
        void onPause(LifecycleOwner owner);
    
        void onStop(LifecycleOwner owner);
    
        void onDestroy(LifecycleOwner owner);
    }
    

    此方式,是回调的observer为FullLifecycleObserver,即要所有的回调方法并且是非反射的实现方式

    4. ReflectiveGenericLifecycleObserver和ClassesInfoCache.CallbackInfo的方式

    class ReflectiveGenericLifecycleObserver implements GenericLifecycleObserver {
        private final Object mWrapped;
        private final CallbackInfo mInfo;
    
        ReflectiveGenericLifecycleObserver(Object wrapped) {
            mWrapped = wrapped;
            mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
        }
    
        @Override
        public void onStateChanged(LifecycleOwner source, Event event) {
            mInfo.invokeCallbacks(source, event, mWrapped);
        }
    }
    
    
    
    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--) {// 通知所有的注解上包含了当前State的方法
                        handlers.get(i).invokeCallback(source, event, mWrapped);
                    }
                }
            }
        }
    

    2.2.3 序列图

    MVVM Lifecycle 序列图

    2.2.4 总结

    1. Activity/Fragment作为LifecycleOwner,LifecycleOwner的唯一接口便是获取Lifecycle
    2. LifecycleRegistry作为Lifecycle的接口实现对象, 提供了注册和删除observer的方法, 在注册后,便会主动通知当前的状态, LifecycleRegistry提供了接口,方便Activity/Fragment在变化时,更新当前管理的state

    2.3 LiveData 下篇博客

    相关文章

      网友评论

        本文标题:Android MVVM 解读 3. Android MVVM

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