美文网首页
Jetpack-Lifecycle 原理解析

Jetpack-Lifecycle 原理解析

作者: 明朗__ | 来源:发表于2021-01-09 14:36 被阅读0次

    介绍

    Lifecycle 它是 Jetpack 组件库的的核心基础 ,具备宿主生命周期感知能力的组件。它能持有组件(如 Activity 或 Fragment)生命周期状态的信息,并且允许其他观察者监听宿主的状态,大大减少了业务代码发生内存泄漏和 NPE 的风险,LiveData 、 ViewModel 组件等也都是基于它来实现的(观察者模式)

    Google developer 介绍

    工程引入

     implementation 'androidx.appcompat:appcompat:1.1.0'
     //或者
     implementation "androidx.lifecycle:lifecycle-common:2.2.0"
     implementation "androidx.lifecycle:lifecycle-common-java8:2.2.0"
     implementation "androidx.lifecycle:lifecycle-runtime:2.2.0"
    

    Lifecycle观察宿主

    每当 Activity/Fragment 的生命周期函数被触发时,该接口的相应同名函数就会在之前或者之后被调用,以此来获得相应生命周期事件变化的通知

    //使用案例
    override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
            lifecycle.addObserver(object : DefaultLifecycleObserver {
                override fun onCreate(owner: LifecycleOwner) {}
    
                override fun onResume(owner: LifecycleOwner) {}
    
                override fun onDestroy(owner: LifecycleOwner) {}
            })
        }
    

    实现原理源码分析

    一、Activity 实现 Lifecycle

    • LifecycleOwner 接口用于标记其实现类具备 Lifecycle 对象
      ComponentActivityFragment 都实现了该接口
     public interface LifecycleOwner {
        @NonNull
        Lifecycle getLifecycle();
     }
     
     class ComponentActivity implements LifecycleOwner{
     
        //LifecycleRegistry观察者添加和事件分发  
       private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
        
          @NonNull
          @Override
          public Lifecycle getLifecycle() {
            return mLifecycleRegistry;
          }
    
          @SuppressLint("RestrictedApi")
          @Override
          protected void onCreate(@Nullable Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                //往Activity上添加一个fragment,用以监听生命周期的变化
               //其目的是为了兼顾不是继承自AppCompactActivity的场景.
                ReportFragment.injectIfNeededIn(this);
          }
    
         public ComponentActivity() {
             //添加观察者
             getLifecycle().addObserver(new LifecycleEventObserver() {
                @Override
                public void onStateChanged(@NonNull LifecycleOwner source,
                        @NonNull Lifecycle.Event event) {
                }
            });
        }
    } 
    
    • Lifecycle接口Lifecycle 声明了 添加观察者 移除观察者等相关函数(抽象)
    public abstract class Lifecycle {
    
      @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
      @NonNull
      AtomicReference<Object> mInternalScopeRef = new AtomicReference<>();
      
      @MainThread 
      public abstract void addObserver(@NonNull LifecycleObserver observer);
    
      @MainThread
      public abstract void removeObserver(@NonNull LifecycleObserver observer);
    
      @MainThread
      @NonNull
      public abstract State getCurrentState();
    }
    
    • Event类(Lifecycle内部静态类)用于抽象 Activity/Fragment 的生命周期事件发生变化时所触发的事件。例如,当 Activity 的每个生命周期事件回调函数(onCreateonStart 等)被触发时都会被抽象为相应的 ON_CREATEON_START 两个 Event
    public enum Event {     
       ON_CREATE,      
       ON_START,      
       ON_RESUME,    
       ON_PAUSE,      
       ON_STOP,      
       ON_DESTROY,    
       ON_ANY  
    }
    
    • State(Lifecycle内部静态类) 类用于标记 Lifecycle 的当前生命周期状态
    public enum State {        
      //当处于 DESTROYED 状态时,Lifecycle 将不会发布其它 Event 值       
      //当 Activity 即将回调 onDestory 时则处于此状态       
      DESTROYED,        
      //已初始化的状态。例如,当 Activity 的构造函数已完成,
      //但还未回调 onCreate 时则处于此状态        
      INITIALIZED,   
      CREATED,       
      STARTED,        
      RESUMED;                
      //如果当前状态大于入参值 state 时,则返回 true    
      public boolean isAtLeast(@NonNull State state) {            
          return compareTo(state) >= 0;       
        } 
    }
    
    • LifecycleRegistry 观察者添加和事件分发
    public class LifecycleRegistry extends Lifecycle {
      private FastSafeIterableMap<LifecycleObserver, ObserverWithState>       
                       mObserverMap =new FastSafeIterableMap<>();
      //一般一个 LifecycleRegistry 对应一个 LifecycleOwner 对象(Activity/Fragment等)
      //mState 就用来标记 LifecycleOwner 对象所处的当前生命周期状态
      private State mState;
      // 持有对 LifecycleOwner 的弱引用,避免内存泄露
      private final WeakReference<LifecycleOwner> mLifecycleOwner;
    
      public LifecycleRegistry(@NonNull LifecycleOwner provider) {
        mLifecycleOwner = new WeakReference<>(provider);
        mState = INITIALIZED;
      }
    }
    
    • LifecycleRegistry addObserver 添加观察者 将观察者包装成ObserverWithState 对象 存储到 mObserverMap
    @Override
    public void addObserver(@NonNull LifecycleObserver observer) {
        //添加新的Observer时,会首先根据宿主的状态计算出它的初始状态,只要不是在onDestroy中注册
       // 的,它的初始状态都是INITIALIZED
        State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
        //接着会把observer包装成ObserverWithState,这个类主要是包含了观察者及其状态。每个事
        //件都会经由这个对象类转发,这个类后面会来分析
        ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
        ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
        //添加到集合,如果之前已经添加过了,则return
        if (previous != null) {
            return;
        }
        LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
        if (lifecycleOwner == null) {
            // it is null we should be destroyed. Fallback quickly
            //如果 LifecycleOwner 对象已经被回收了,则直接返回
            return;
        }
        //如果 isReentrance 为 true,则说明此时以下两种情况至少有一个成立:     
        //1. mAddingObserverCounter != 0。会出现这种情况,是由于开发者先添加了一个        
        //   LifecycleObserver ,当还在向其回调事件的过程中,
        //在回调函数里又再次调用了 addObserver 方法添加了一个新的 LifecycleObserver       
       //2.mHandlingEvent 为 true。即此时正处于向外回调 Lifecycle.Event 的状态
    
        boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
        State targetState = calculateTargetState(observer);
        //递增加一,标记当前正处于向新添加的 LifecycleObserver 回调 Event 值的过程
        mAddingObserverCounter++;
         
        //拿观察者的状态和宿主当前状态做比较,如果小于0,说明两者状态还没有对齐
        while ((statefulObserver.mState.compareTo(targetState) < 0
                && mObserverMap.contains(observer))) {
            //将 observer 已经遍历到的当前的状态值 mState 保存下来
            pushParentState(statefulObserver.mState);
            //向 observer 回调进入“statefulObserver.mState”前需要收到的 Event 值
            statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState));
           //移除 mState
            popParentState();
            // mState / subling may have been changed recalculate
            targetState = calculateTargetState(observer);
        }
    
        if (!isReentrance) {
            // we do sync only on the top level.
            sync();
        }
        mAddingObserverCounter--;
    }
    
    • ObserverWithState 将外界传入的 LifecycleObserver 对象传给 Lifecycling 进行类型包装,将反射逻辑和接口回调逻辑都给汇总综合成一个新的 LifecycleEventObserver 对象,从而使得 Event 分发过程都统一为一个入口
    static class ObserverWithState {
            State mState;
            LifecycleEventObserver mLifecycleObserver;
    
            ObserverWithState(LifecycleObserver observer, State initialState) {
                mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
                mState = initialState;
            }
    
            void dispatchEvent(LifecycleOwner owner, Event event) {
                //再一次根据需要分发的事件类型反推出该观察者的状态
                State newState = getStateAfter(event);
                mState = min(mState, newState);
                //把事件分发给被包装的对象,完成本次流程。
                mLifecycleObserver.onStateChanged(owner, event);
                mState = newState;
            }
        }
        
     //再一次根据需要分发的事件类型反推出该观察者的状态,这样的好处是事件与状态对应,不会出现跳跃   
    static State getStateAfter(Event event) {
            switch (event) {
                case ON_CREATE:
                case ON_STOP:
                    return CREATED;
                case ON_START:
                case ON_PAUSE:
                    return STARTED;
                case ON_RESUME:
                    return RESUMED;
                case ON_DESTROY:
                    return DESTROYED;
                case ON_ANY:
                    break;
            }
            throw new IllegalArgumentException("Unexpected event value " + event);
        }    
    
    • Lifecycling.lifecycleEventObserver 获取观察者对象类型 根据传入的不同观察者对象类型返回不同的观察者对象
     @NonNull
        static LifecycleEventObserver lifecycleEventObserver(Object object) {
            boolean isLifecycleEventObserver = object instanceof LifecycleEventObserver;
            boolean isFullLifecycleObserver = object instanceof FullLifecycleObserver;
            if (isLifecycleEventObserver && isFullLifecycleObserver) {
                return new FullLifecycleObserverAdapter((FullLifecycleObserver) object,
                        (LifecycleEventObserver) object);
            }
            
            if (isFullLifecycleObserver) {
                return new FullLifecycleObserverAdapter((FullLifecycleObserver) object, null);
            }
            
            if (isLifecycleEventObserver) {
                return (LifecycleEventObserver) object;
            }
        ......一些反射逻辑....
    }        
    
    • LifecycleEventObserverFullLifecycleObserver 都实现了 LifecycleObserver (Java多态)
    public interface LifecycleObserver {
    
    }
    
    public interface LifecycleEventObserver extends LifecycleObserver {
    
        void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event);
    }
    
    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);
    }
    
    • FullLifecycleObserverAdapter 实现了 LifecycleEventObserver 接口,用于在收到 Lifecycle 生命周期事件状态变化时,对其两个构造函数参数( FullLifecycleObserverLifecycleEventObserver)进行生命周期事件做转发
    class FullLifecycleObserverAdapter implements LifecycleEventObserver {
    
        private final FullLifecycleObserver mFullLifecycleObserver;
        private final LifecycleEventObserver mLifecycleEventObserver;
    
        FullLifecycleObserverAdapter(FullLifecycleObserver fullLifecycleObserver,
                LifecycleEventObserver lifecycleEventObserver) {
            mFullLifecycleObserver = fullLifecycleObserver;
            mLifecycleEventObserver = lifecycleEventObserver;
        }
        //进行生命周期事件转发
        @Override
        public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
            switch (event) {
                case ON_CREATE:
                    mFullLifecycleObserver.onCreate(source);
                    break;
                case ON_START:
                    mFullLifecycleObserver.onStart(source);
                    break;
                case ON_RESUME:
                    mFullLifecycleObserver.onResume(source);
                    break;
                case ON_PAUSE:
                    mFullLifecycleObserver.onPause(source);
                    break;
                case ON_STOP:
                    mFullLifecycleObserver.onStop(source);
                    break;
                case ON_DESTROY:
                    mFullLifecycleObserver.onDestroy(source);
                    break;
                case ON_ANY:
                    throw new IllegalArgumentException("ON_ANY must not been send by anybody");
            }
            if (mLifecycleEventObserver != null) {
                mLifecycleEventObserver.onStateChanged(source, event);
            }
        }
    }
    
    • 以上对如何添加观察者以及这些观察者如何接受宿主生命周期变更事件做了分析,接下来分析宿主的生命周期变更是怎么分发出去的 还记得ComponentActivity中添加的那个ReportFragment
     class ComponentActivity implements LifecycleOwner{
     
        //LifecycleRegistry观察者添加和事件分发  
       private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
        
          @NonNull
          @Override
          public Lifecycle getLifecycle() {
            return mLifecycleRegistry;
          }
    
          @SuppressLint("RestrictedApi")
          @Override
          protected void onCreate(@Nullable Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                //往Activity上添加一个fragment,用以监听生命周期的变化
               //其目的是为了兼顾不是继承自AppCompactActivity的场景.
                ReportFragment.injectIfNeededIn(this);
          }
    }
    
    • ReportFragment 获取到 AppCompatActivity 的事件变化通知,最终调用 LifecycleRegistryhandleLifecycleEvent(Lifecycle.Event) 方法将 Lifecycle.Event 传递出去。此时,LifecycleRegistry 就拿到了 Lifecycle.Event
    public class ReportFragment extends Fragment {
       //添加到Activity
       public static void injectIfNeededIn(Activity activity) {
          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();
          }
       }
    
       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);
            }
         }
       }
      
       @Override
       public void onActivityCreated(Bundle savedInstanceState) {
          super.onActivityCreated(savedInstanceState);
          dispatch(Lifecycle.Event.ON_CREATE);
       }
    
       @Override
       public void onStart() {
          super.onStart();
          dispatch(Lifecycle.Event.ON_START);
       }
    
       @Override
       public void onResume() {
        super.onResume();
        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);
      }
    }
    
    • 分发宿状态的 handleLifecycleEvent 该方法会根据接收到的 Event 值换算出对应的 State 值,然后更新本地的 mState,再向所有 Observer 进行事件通知,最终还是会调用到 ObserverWithStatedispatchEvent 方法,所以后边重点关注 dispatchEvent 方法即可
    public class LifecycleRegistry extends Lifecycle {
      private FastSafeIterableMap<LifecycleObserver, ObserverWithState>       
                       mObserverMap =new FastSafeIterableMap<>();
    
       public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
        //根据接收到的 Event 值换算出对应的 State 值
        State next = getStateAfter(event);
        moveToState(next);
       }
    
       private void moveToState(State next) {
        if (mState == next) {
            return;
        }
        mState = next;
        if (mHandlingEvent || mAddingObserverCounter != 0) {
            mNewEventOccurred = true;
            // we will figure out what to do on upper level.
            return;
        }
        mHandlingEvent = true;
        sync();
        mHandlingEvent = false;
      }
    }
    
    • sync() 宿主生命周期状态同步和分发
    private void sync() {
            //mLifecycleOwner.get() 获取到的是宿主(Activity/Fragment)
            LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
            if (lifecycleOwner == null) {
                throw new IllegalStateException("LifecycleOwner of this LifecycleRegistry is already"
                        + "garbage collected. It is too late to change lifecycle state.");
            }
            while (!isSynced()) {
                mNewEventOccurred = false;
                 //如果宿主当前转态 小于 mObserverMap集合中最先添加的那个观察者的状态
                //则说明宿主可能发生了状态回退,比如当前是RESUMED状态,执行了onPause则回退到
                //STARTED状态
               //此时调用backwardPass把集合中的每个一观察者分发一个on_pause事件,并同步它的状态。
                if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
                    backwardPass(lifecycleOwner);
                }
                //如果宿主当前转态 大于 mObserverMap集合中最先添加的那个观察者的状态
            //则说明宿主可能发生了状态前进,比如当前是STARTED状态,执行了onResume则前进到
            //RESUMED状态
            //此时调用forwardPass把集合中的每个一观察者分发一个on_resume事件,并同步它的状态。
                Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
                if (!mNewEventOccurred && newest != null
                        && mState.compareTo(newest.getValue().mState) > 0) {
                    forwardPass(lifecycleOwner);
                }
            }
            mNewEventOccurred = false;
        }
    
    • backwardPassforwardPass 遍历Map中保存的观察者 进行事件分发
      注意mNewEventOccurred 这个boolean值开关 是在有新的事件过来时能及时终止
      while循环分发没有意义的事件
     private void backwardPass(LifecycleOwner lifecycleOwner) {
         Iterator<Entry<LifecycleObserver, ObserverWithState>> descendingIterator =
                mObserverMap.descendingIterator();
         while (descendingIterator.hasNext() && !mNewEventOccurred) {
            Entry<LifecycleObserver, ObserverWithState> entry = 
            descendingIterator.next();
            ObserverWithState observer = entry.getValue();
            while ((observer.mState.compareTo(mState) > 0 && !mNewEventOccurred
                    && mObserverMap.contains(entry.getKey()))) {
                Event event = downEvent(observer.mState);
                pushParentState(getStateAfter(event));
                //生命周期事件分发
                observer.dispatchEvent(lifecycleOwner, event);
                popParentState();
            }
        }
       }
    

    二、 Fragment 实现 Lifecycle Fragment的实现和add到 AppCompatActivity中的 ReportFragment就打同小异了 一看就明白

    public class Fragment implements LifecycleOwner{
    
       LifecycleRegistry mLifecycleRegistry;
    
       public Fragment() {
        initLifecycle();
       }
       
       private void initLifecycle() {
        mLifecycleRegistry = new LifecycleRegistry(this);
        if (Build.VERSION.SDK_INT >= 19) {
            mLifecycleRegistry.addObserver(new LifecycleEventObserver() {
                @Override
                public void onStateChanged(@NonNull LifecycleOwner source,
                        @NonNull Lifecycle.Event event) {
                    if (event == Lifecycle.Event.ON_STOP) {
                        if (mView != null) {
                            mView.cancelPendingInputEvents();
                        }
                    }
                }
            });
        }
      }
    
      @Override
      @NonNull
       public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
       }
       //事件分发
      void performCreate(){
         mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
      }
      
       void performStart(){
         mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
       }
    
       void performResume(){
         mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
       }  
    }
    

    总结

    • LifecycleOwner: Activity/Fragment 都实现了该接口,用以声明它是一个能够提供生命周期事件的宿主。同时必须复写getLifecycle()方法提供一个Lifecycle对象
    • Lifecycle:是一个抽象类,里面定义了两个枚举State宿主的状态,Event 需要分发的事件的类型
    • LifecycleRegistry: 是 Lifecycle 的唯一实现类,主要用来负责注册 Observer(观察者),以及分发宿主状态事件给它们


      1610167303751.jpg

    使用场景介绍

    对平时开发中需要感知(Fragment/Activity)生命周期逻辑的地方 可以继承LifecycleEventObserver或者 DefaultLifecycleObserver 并添加到 (Fragment/Activity)的 LifecycleRegistry中来观察 (Fragment/Activity)生命周期的变化 而做出对应的业务逻辑变化 (Ps:以前我们可能是在BaseActivity 或者BaseFragment的onStart()和onStop()添加对应生命周期相关的逻辑 )

    class LocationObserver extends DefaultLifecycleObserver{
        //宿主执行了onstart时,会分发该事件
        void onStart(@NotNull LifecycleOwner owner){
            //开启定位
        }
      
       //宿主执行了onstop时 会分发该事件
       void onStop(@NotNull LifecycleOwner owner){
           //停止定位
       }
    }
    //2. 注册观察者,观察宿主生命周期状态变化
    class MyFragment extends Fragment{
      public void onCreate(Bundle bundle){
        LocationObserver observer =new LocationObserver()
        //添加观察者
        getLifecycle().addObserver(observer);
      }
     }
    

    相关文章

      网友评论

          本文标题:Jetpack-Lifecycle 原理解析

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