android源码(1)LiveData源码

2、LiveData如何感知生命周期?

总结:首先看数据:LiveData中的 mObservers 和 LifecycleRegistry 中的 mObserverMap。

LiveData中:
// key: observer; value:  new LifecycleBoundObserver(owner, observer)
SafeIterableMap<Observer<T>, ObserverWrapper> mObservers = new SafeIterableMap<>();

public void observe(LifecycleOwner owner, Observer<T> observer) {
      
        LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer);
        mObservers.putIfAbsent(observer, wrapper);
        owner.getLifecycle().addObserver(wrapper);
}

LifecycleRegistry中:

//  key:LifecycleBoundObserver(owner, observer)    
//  value : ObserverWithState( LifecycleBoundObserver(owner, observer),   initialState)
FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap =  new FastSafeIterableMap<>();


public void addObserver(LifecycleObserver observer) {

        State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
        ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
        ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
}

说白了就这两条线:
1、从 livedata 的 setValue()触发:使用mObservers中存储的observer更新数据;
2、从 fragment 的 onCreat/onStart/…等触发: 使用LifecycleRegistry中存储的observer(不用mObservers)更新数据。

android源码(1)LiveData源码_第1张图片
关键对象:

1、LiveData: 作为数据入口,维护观察者和被观察者的关系
2、Observer:数据改变后最终触发的函数,回调接口,调用端实现
3、LifecycleOwner: Activity, Fragment 提供 Lifecycle
4、Lifecycle, LifecycleRegistry
5、LifecycleObserver,GenericLifecycleObserver, LifecycleBoundObserver: 封装Observer, LifecycleOwner 对象

SupportActivity中:

public class SupportActivity extends Activity implements LifecycleOwner {

		 @Override
		    @SuppressWarnings("RestrictedApi")
		    protected void onCreate(@Nullable Bundle savedInstanceState) {
		        super.onCreate(savedInstanceState);
		        ReportFragment.injectIfNeededIn(this);
		    }
} 

上面关键的一句ReportFragment.injectIfNeededIn(this);下面看ReportFragment各生命周期:

 public class ReportFragment extends Fragment {
		
		 @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去处理生命周期事件,把生命周期 Event 传递给 LifecycleObserver
		                ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
		            }
		        }
		    }
}

LifecycleRegistry就是LifeCycle的登记处,它以弱引用的方式持有了当前的Activity。
至此:当lifecycle发生变化时,handleLifecycleEvent 会通过 getStateAfter()方法获取当前应处的状态并修改mState值,紧接着遍历所有 ObserverWithState并调用他们的sync方法来同步且通知LifecycleObserver状态发生变化。

public class LifecycleRegistry extends Lifecycle {

		    	public LifecycleRegistry(@NonNull LifecycleOwner provider) {
			           mLifecycleOwner = new WeakReference<>(provider);
			           mState = INITIALIZED;
			      }
			      
               //设置当前状态并通知观察者
			    public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
		         	  // 根据生命周期事件得到对应的状态
			          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() {
				        LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
				        if (lifecycleOwner == null) {
				            Log.w(LOG_TAG, "LifecycleOwner is garbage collected, you shouldn't try dispatch "
				                    + "new events from it.");
				            return;
				        }
				        while (!isSynced()) {
				            mNewEventOccurred = false;
				            //比较当前的生命周期和Map中第一个的观察者的生命周期
				            if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
				                 // 倒序遍历,通知LifecycleObserver,去修改状态
				                backwardPass(lifecycleOwner);
				            }
				            Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
				            if (!mNewEventOccurred && newest != null
				                    && mState.compareTo(newest.getValue().mState) > 0) {
				                    // 正序遍历,通知观察者,去修改状态 
				                forwardPass(lifecycleOwner);
				            }
				        }
				        mNewEventOccurred = false;
				    }

          //  key:LifecycleBoundObserver(owner, observer)    
          //  value : ObserverWithState( LifecycleBoundObserver(owner, observer),   initialState)
             private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap =  new FastSafeIterableMap<>();
            
					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();
					            }
					        }
					    }


				private void forwardPass(LifecycleOwner lifecycleOwner) {
				        Iterator<Entry<LifecycleObserver, ObserverWithState>> ascendingIterator =
				                mObserverMap.iteratorWithAdditions();
				        while (ascendingIterator.hasNext() && !mNewEventOccurred) {
				            Entry<LifecycleObserver, ObserverWithState> entry = ascendingIterator.next();
				            ObserverWithState observer = entry.getValue();
				            while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred
				                    && mObserverMap.contains(entry.getKey()))) {
				                pushParentState(observer.mState);
				                //生命周期变化后
				                observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
				                popParentState();
				            }
				        }
				    }
	}


ObserverWithState中:

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 : LifecycleBoundObserver(owner, observer)
            mLifecycleObserver.onStateChanged(owner, event);  
            mState = newState;
        }
    }

LifecycleBoundObserver是LiveData的内部类:

LiveData 和 生命周期的关系基本操作:
生命周期正常的时候, addObserver 注册观察者;生命周期结束的时候 removeObserver 取消观察者

     class LifecycleBoundObserver extends ObserverWrapper implements GenericLifecycleObserver {
       
       .........
       
        @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());
        }
   }

LiveData中:

@MainThread
    public void removeObserver(@NonNull final Observer<T> observer) {
        assertMainThread("removeObserver");
        ObserverWrapper removed = mObservers.remove(observer);
        if (removed == null) {
            return;
        }
        removed.detachObserver();
        removed.activeStateChanged(false);
    }

ObserverWrapper中:

 private abstract class ObserverWrapper {
  
        void activeStateChanged(boolean newActive) {
            if (newActive == mActive) {
                return;
            }
            
         ........
         
            if (mActive) {
                dispatchingValue(this);
            }
       
    }

liveData中dispatchingValue()

 // key: observer  ;   value: LifecycleBoundObserver(owner, observer)
 private SafeIterableMap<Observer<T>, ObserverWrapper> mObservers = new SafeIterableMap<>();

private void dispatchingValue(@Nullable ObserverWrapper initiator) {
        if (mDispatchingValue) {
            mDispatchInvalidated = true;
            return;
        }
        mDispatchingValue = true;
        do {
            mDispatchInvalidated = false;
            //initiator :LifecycleBoundObserver(owner, observer)
            //class LifecycleBoundObserver extends ObserverWrapper implements GenericLifecycleObserver
            if (initiator != null) {
                considerNotify(initiator);  //看这里
                initiator = null;
            } else {
                for (Iterator<Map.Entry<Observer<T>, ObserverWrapper>> iterator =
                        mObservers.iteratorWithAdditions(); iterator.hasNext(); ) {
                    //mObservers看上面
                    considerNotify(iterator.next().getValue());    //看这里
                    if (mDispatchInvalidated) {
                        break;
                    }
                }
            }
        } while (mDispatchInvalidated);
        mDispatchingValue = false;
    }


//class LifecycleBoundObserver extends ObserverWrapper implements GenericLifecycleObserver
//参数observer :LifecycleBoundObserver(owner, observer)
private void considerNotify(ObserverWrapper observer) {
        if (!observer.mActive) {
            return;
        }
     
        if (!observer.shouldBeActive()) {
            observer.activeStateChanged(false);
            return;
        }
        if (observer.mLastVersion >= mVersion) {
            return;
        }
        observer.mLastVersion = mVersion;
         // 最终调用观察者的onChanged()回调
        observer.mObserver.onChanged((T) mData);    //最后到这里
    }

3、LiveData注册Observer

添加观察者过程实际上是把 Observer 传递给 LiveData 对象 和 LifecycleRegistry 对象。

我们一般在fragment中这样用:

		       liveData.observe(this, new Observer<Object>() {
		            @Override
		            public void onChanged(@Nullable Object o) {
		
		            }
		        });

进入observe方法:

            // key: observer  ;   value:  new LifecycleBoundObserver(owner, observer)
             private SafeIterableMap<Observer<T>, ObserverWrapper> mObservers = new SafeIterableMap<>();
             
                 @MainThread
			    public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<T> observer) {
			        if (owner.getLifecycle().getCurrentState() == DESTROYED) {
			            return;
			        }
			        // 将LifecycleOwner和Observer包装了一层
			        LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer);
			        
			        // 判断Observer有没有被添加过,如果没有则添加到一个HashMap中mObservers
			        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 和 observer 的 LifecycleBoundObserver添加到LifecycleRegistry
			        owner.getLifecycle().addObserver(wrapper);
			    }

继续进入LifecycleRegistry的addObserver():LifecycleRegistry 中存储 observer:

//  key:LifecycleBoundObserver(owner, observer)    
//  value : ObserverWithState( LifecycleBoundObserver(owner, observer),   initialState)
private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap =
            new FastSafeIterableMap<>();
            
     @Override
    public void addObserver(@NonNull LifecycleObserver observer) {
        State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
              // 将LifecycleObserver包装为ObserverWithState
        ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
           // 如果没有保存过就存入mObserverMap
           // mObserverMap是一个可以在迭代过程中修改的HashMap
        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--;
    }

4、LiveData数据设置

LiveData有两种方式设置数据,第一种setValue(),在主线程中使用
而 postValue在异步线程中使用:

			 @MainThread
			    protected void setValue(T value) {
			        assertMainThread("setValue");
			        mVersion++;
			        mData = value;
			        dispatchingValue(null);    //前面已经有了dispatchingValue的源码
			    }

postValue方法:

通过一个以MainLooper作为Looper的Handler将mPostValueRunnable发送到主线程上,最终还是调用了setValue()。setValue()中调用了dispatchingValue(),进而调用了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);
			        }
			    };

ArchTaskExecutor 使用了代理模式, 实际函数执行类是 DefaultTaskExecutor:

			public class DefaultTaskExecutor extends TaskExecutor {
				       private final Object mLock = new Object();
					    private ExecutorService mDiskIO = Executors.newFixedThreadPool(2);
					
					    @Nullable
					    private volatile Handler mMainHandler;
					
					    @Override
					    public void executeOnDiskIO(Runnable runnable) {
					        mDiskIO.execute(runnable);
					    }
					
					    @Override
					    public void postToMainThread(Runnable runnable) {
					        if (mMainHandler == null) {
					            synchronized (mLock) {
					                if (mMainHandler == null) {
					                    mMainHandler = new Handler(Looper.getMainLooper());
					                }
					            }
					        }
					        //noinspection ConstantConditions
					        mMainHandler.post(runnable);
					    }
					
					    @Override
					    public boolean isMainThread() {
					        return Looper.getMainLooper().getThread() == Thread.currentThread();
					    }
			}

你可能感兴趣的:(android)