Jetpack-Lifecycle 原理解析

2021-01-09  本文已影响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

 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) {
            }
        });
    }
} 
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();
}
public enum Event {     
   ON_CREATE,      
   ON_START,      
   ON_RESUME,    
   ON_PAUSE,      
   ON_STOP,      
   ON_DESTROY,    
   ON_ANY  
}
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;       
    } 
}
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;
  }
}
@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--;
}
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);
    }    
 @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;
        }
    ......一些反射逻辑....
}        
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);
}
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);
        }
    }
}
 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 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);
  }
}
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;
  }
}
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;
    }
 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);
   }  
}

总结

使用场景介绍

对平时开发中需要感知(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);
  }
 }
上一篇下一篇

猜你喜欢

热点阅读