44. LifeCycle与LiveData

LifeCycle

LifeCycle是Google提供的用于监控Activity和Fragment生命周期的一种解耦的实现方式

使用方法举例

如下面的代码,当Activity生命周期变化时,在MyLifeCycleListener中就可以收到相应的回调

public class MainActivity extends AppCompatActivity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyLifeCycleListener lifeCycleListener = new MyLifeCycleListener();
        getLifecycle().addObserver(lifeCycleListener);
    }
}

public class MyLifeCycleListener implements LifecycleObserver {
    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    void onCreate(LifecycleOwner owner) {

    }
    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    void onStart(LifecycleOwner owner) {
    }
    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    void onStop(LifecycleOwner owner) {
    }
    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    void onResume(LifecycleOwner owner) {
    }
    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    void onPause(LifecycleOwner owner) {
    }
    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    void onDestroy(LifecycleOwner owner) {
    }
    @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
    void onAny(LifecycleOwner owner) {
    }
}
怎么做到的?

AppCompatActivity -> FragmentActivity -> ComponentActivity
在ComponentActivity中创建了一个LifecycleRegistry(继承自Lifecycle),所以getLifecycle()获取到的就是这个对象

private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);

进入它的addObserver方法中

    @Override
    public void addObserver(@NonNull LifecycleObserver observer) {
        State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
        //看这一行
        ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
        ......
    }

    ObserverWithState(LifecycleObserver observer, State initialState) {
        mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
        mState = initialState;
    }

    @NonNull
    static LifecycleEventObserver lifecycleEventObserver(Object object) {
          ......
          return new ReflectiveGenericLifecycleObserver(object);
    }

    ReflectiveGenericLifecycleObserver(Object wrapped) {
        ......
        mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
    }

    CallbackInfo getInfo(Class klass) {
        ......
        existing = createInfo(klass, null);
        return existing;
    }

最终在createInfo方法中发现它遍历了我们MyLifeCycleListener类中所有的注解方法并保存了起来。也就是说在addObserver的时候就已经通过注解和反射拿到相应的生命周期方法了

    private CallbackInfo createInfo(Class klass, @Nullable Method[] declaredMethods) {
        ......

        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;
                ......
            }
            Lifecycle.Event event = annotation.value();

            if (params.length > 1) {
                callType = CALL_TYPE_PROVIDER_WITH_EVENT;
                ......
            }
            ......
            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;
    }
怎么调用生命周期方法的?

我们进入ComponentActivity中查找真相,在ComponentActivity中你会发现这样一行代码。看到这一行是不是想到了Glide中对生命周期监听的实现方式?将 一个空白的fragment添加到Activity中,fragment可以响应activity的生命周期,从而实现对生命周期的监听

    ReportFragment.injectIfNeededIn(this);
    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();
            manager.executePendingTransactions();
        }
    }

在ReportFragment中当执行到相应的生命周期方法时,最终通过dispatch方法将回调分发出去

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

LiveData

LiveData你可以把它当作一个可以替换EventBus的实现方案。LiveData 是一个抽象类,它的实现子类有 MutableLiveData ,MediatorLiveData。在实际使用中,用得比较多的是 MutableLiveData

用LiveData实现一个“EventBus”
public class EventBus {
    private Map> bus;

    private static EventBus liveDataBus = new EventBus();

    private EventBus() {
        bus = new HashMap<>();
    }

    public static EventBus getInstance() {
        return liveDataBus;
    }

    public synchronized  MutableLiveData with(String key, Class type) {
        if (!bus.containsKey(key)) {
            bus.put(key, new MutableLiveData());
        }
        return (MutableLiveData) bus.get(key);
    }
}
 
 

当我们需要监听某一数据变化的时候

EventBus.getInstance().with("list", ArrayList.class)
                .observe(this, arrayList -> {
                    if (arrayList != null) {
                        Log.i("", "收到了数据" + arrayList.toString());
                    }
                });       

当数据发生变化,要通知监听者的时候

        ArrayList data = new ArrayList<>();    
        data.add("1");
        EventBus.getInstance().with("list", ArrayList.class).postValue(data);

你可能感兴趣的:(44. LifeCycle与LiveData)