Eveloper. Android. Google. Cn/topic/libra…

By default, integrate v7 package (version larger than 26.1.0). At this time, look at the overall dependency.



Lifecycler packages are not integrated, but they are by default. Now let’s look at activities and fragments.

V4 supports activities and Fragments implement the LifecycleOwner interface by default. It looks like Google has made V4 rely on licFCycle by default.

Add the following to the main build.gradle:

allprojects{  repositories{      jcenter()      maven{url'https://maven.google.com'
}}Copy the code

Then add the following to your app’s build.gradle:

implementation "Android. Arch. Lifecycle: extensions: 1.0.0"
annotationProcessor "Android. Arch. Lifecycle: the compiler: 1.0.0"Copy the code

Once compiled, start writing some simple code (usage will not be discussed, this section will focus on some source code, see the official documentation for specific usage, as well as many excellent blogs).

First write a data class:

import android.app.Application;
import android.arch.lifecycle.AndroidViewModel;
import android.arch.lifecycle.MutableLiveData;

/**
 * Created by 10488 on 2017-11-09.
 */

public class MainModel extends AndroidViewModel {

    private MutableLiveData<String> mMutableLiveData = new MutableLiveData<>();

    public MainModel(Application application) {
        super(application);
    }

    public MutableLiveData<String> getMutableLiveData() {
        returnmMutableLiveData; } /** * get data. */ public voidrequestGetData() {
        try {
            Thread.sleep(1000);
            getMutableLiveData().setValue("Acquired data");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
@Override
protected void onCleared() {
    Log.d("MainModel"."Clean up resources");
}}
Copy the code

Then the activity:

import android.annotation.SuppressLint;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;


/**
 * @author 10488
 * @date 2017-11-09
 */

@SuppressLint("Registered")
public class MainActivity extends AppCompatActivity {

    private MainModel mMainModel;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); mMainModel = ViewModelProviders.of(this).get(MainModel.class); mMainModel.getMutableLiveData().observe(this, new Observer<String>() { @Override public void onChanged(@Nullable String s) { Toast.makeText(MainActivity.this, s, Toast.LENGTH_SHORT).show(); }}); findViewById(R.id.tv).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mMainModel.requestGetData(); }}); }}Copy the code

The function is very simple, is to click the button, suppose to get the data, and then get the data toast.

Let’s start with a brief analysis of the source code, starting with the activity, and look at this line of code:

 mMainModel = ViewModelProviders.of(this).get(MainModel.class);Copy the code

I’m curious why I don’t just use “new”. When I look at “class”, I think of reflection.

First of all, click on the “of” method,

@mainThread public static ViewModelProvider of(@nonnull FragmentActivity Activity) {// sDefaultFactory is created initializeFactoryIfNeeded(checkApplication(activity));returnnew ViewModelProvider(ViewModelStores.of(activity), sDefaultFactory); } public ViewModelProvider(@NonNull ViewModelStore store, @NonNull Factory factory) { mFactory = factory; this.mViewModelStore = store; } /** * This factory has only one object created by reflection (holding application references) */ @suppressWarnings ("WeakerAccess")public static class DefaultFactory extends ViewModelProvider.NewInstanceFactory {    private Application mApplication;

    /**
     * Creates a {@code DefaultFactory}
     *
     * @param application an application to pass in {@link AndroidViewModel}
     */
    public DefaultFactory(@NonNull Application application) {
        mApplication = application;
    }

    @NonNull
    @Override
    public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
        if (AndroidViewModel.class.isAssignableFrom(modelClass)) {
            //noinspection TryWithIdenticalCatches
            try {
                return modelClass.getConstructor(Application.class).newInstance(mApplication);
            } catch (NoSuchMethodException e) {
                throw new RuntimeException("Cannot create an instance of " + modelClass, e);
            } catch (IllegalAccessException e) {
                throw new RuntimeException("Cannot create an instance of " + modelClass, e);
            } catch (InstantiationException e) {
                throw new RuntimeException("Cannot create an instance of " + modelClass, e);
            } catch (InvocationTargetException e) {
                throw new RuntimeException("Cannot create an instance of "+ modelClass, e); }}returnsuper.create(modelClass); }}Copy the code

There is also a method of is this, is their inheritance. ViewModelProvider NewInstanceFactory, realize the create method, returns the object they want.

@MainThread
public static ViewModelProvider of(@NonNull Fragment fragment, @NonNull Factory factory) {
    checkApplication(checkActivity(fragment));
    return new ViewModelProvider(ViewModelStores.of(fragment), factory);
}Copy the code

Viewmodelproviders.of (this).get(mainModel.class) get(mainModel.class) And it’s also putting this viewModel into mViewModelStore, so let’s talk about what mViewModelStore is and why it’s used.

@NonNull
public <T extends ViewModel> T get(@NonNull Class<T> modelClass) {
    String canonicalName = modelClass.getCanonicalName();
    if (canonicalName == null) {
        throw new IllegalArgumentException("Local and anonymous classes can not be ViewModels");
    }
    return get(DEFAULT_KEY + ":" + canonicalName, modelClass);
}

@NonNull
@MainThread
public <T extends ViewModel> T get(@NonNull String key, @NonNull Class<T> modelClass) {
    ViewModel viewModel = mViewModelStore.get(key);

    if (modelClass.isInstance(viewModel)) {
        //noinspection unchecked
        return (T) viewModel;
    } else {
        //noinspection StatementWithEmptyBody
        if(viewModel ! = null) { // TODO:log a warning.
        }
    }

    viewModel = mFactory.create(modelClass);
    mViewModelStore.put(key, viewModel);
    //noinspection unchecked
    return (T) viewModel;
}

Copy the code

Let’s go back to the ViewModelProviders of method

@MainThread
public static ViewModelProvider of(@NonNull FragmentActivity activity) {
    initializeFactoryIfNeeded(checkApplication(activity));
    return new ViewModelProvider(ViewModelStores.of(activity), sDefaultFactory);
}Copy the code

Next we’ll look at ViewModelStores. Of (Activity). MViewModelStore refers to the object returned by ViewModelStores. This class is simple:

import static android.arch.lifecycle.HolderFragment.holderFragmentFor;

import android.support.annotation.MainThread;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;

/**
 * Factory methods for {@link ViewModelStore} class.
 */
@SuppressWarnings("WeakerAccess")
public class ViewModelStores {

    private ViewModelStores() {
    }

    /**
     * Returns the {@link ViewModelStore} of the given activity.
     *
     * @param activity an activity whose {@code ViewModelStore} is requested
     * @return@mainThread public static ViewModelStore of(@nonnull FragmentActivity activity) {a {@code ViewModelStore} */return holderFragmentFor(activity).getViewModelStore();
    }

    /**
     * Returns the {@link ViewModelStore} of the given fragment.
     *
     * @param fragment a fragment whose {@code ViewModelStore} is requested
     * @return a {@code ViewModelStore}
     */
    @MainThread
    public static ViewModelStore of(@NonNull Fragment fragment) {
        returnholderFragmentFor(fragment).getViewModelStore(); }}Copy the code

Now we’re only looking at activity-related, so continue looking at holderFragmentFor(Activity).getViewModelStore();

Next trace code:

private Map<Activity, HolderFragment> mNotCommittedActivityHolders = new HashMap<>();

/**
 * @hide
 */
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public static HolderFragment holderFragmentFor(FragmentActivity activity) {
    returnsHolderFragmentManager.holderFragmentFor(activity); } /** * main code */ HolderFragment holderFragmentFor(FragmentActivity activity) {FragmentManager FM = activity.getSupportFragmentManager(); HolderFragment holder = findHolderFragment(fm);if(holder ! = null) {return holder;
    }
    holder = mNotCommittedActivityHolders.get(activity);
    if(holder ! = null) {return holder;
    }

    if(! mActivityCallbacksIsAdded) { mActivityCallbacksIsAdded =true;
        activity.getApplication().registerActivityLifecycleCallbacks(mActivityCallbacks);
    }
    holder = createHolderFragment(fm);
    mNotCommittedActivityHolders.put(activity, holder);
    return holder;
}

private static HolderFragment findHolderFragment(FragmentManager manager) {
    if (manager.isDestroyed()) {
        throw new IllegalStateException("Can't access ViewModels from onDestroy");
    }

    Fragment fragmentByTag = manager.findFragmentByTag(HOLDER_TAG);
    if(fragmentByTag ! = null && ! (fragmentByTag instanceof HolderFragment)) { throw new IllegalStateException("Unexpected "
                + "fragment instance was returned by HOLDER_TAG");
    }
    return (HolderFragment) fragmentByTag;
}

private static HolderFragment createHolderFragment(FragmentManager fragmentManager) {
    HolderFragment holder = new HolderFragment();
    fragmentManager.beginTransaction().add(holder, HOLDER_TAG).commitAllowingStateLoss();
    return holder;
}

Copy the code

HolderFragment is a Fragment. First of all, on the base of the current activity to find the current holderFragment FragmentManager, the activity of code executed here for the first time, must be empty, so keep from mNotCommittedActivityHolders when, MNotCommittedActivityHolders is a hashmap, of course, is empty, so call processing application to perform the activity life cycle, registerActivityLifecycleCallbacks, If you don’t know this, it’s time to brush up on the basics.

private ActivityLifecycleCallbacks mActivityCallbacks =
        new EmptyActivityLifecycleCallbacks() {
            @Override
            public void onActivityDestroyed(Activity activity) {
                HolderFragment fragment = mNotCommittedActivityHolders.remove(activity);
                if(fragment ! = null) { Log.e(LOG_TAG,"Failed to save a ViewModel for "+ activity); }}};Copy the code

The following code adds the current fragment to the current activity, using the activity as the key to add the current fragment. Now let’s see what HolderFragment did.

/** * @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public class HolderFragment extends Fragment { private static  final String LOG_TAG ="ViewModelStores";

    private static final HolderFragmentManager sHolderFragmentManager = new HolderFragmentManager();

    /**
     * @hide
     */
    @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
    public static final String HOLDER_TAG =
            "android.arch.lifecycle.state.StateProviderHolderFragment";

    private ViewModelStore mViewModelStore = new ViewModelStore();

    public HolderFragment() {
        setRetainInstance(true);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sHolderFragmentManager.holderFragmentCreated(this);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mViewModelStore.clear();
    }

    public ViewModelStore getViewModelStore() {
        return mViewModelStore;
    }
Copy the code

HolderFragment has a ViewModelStore in it, which is the mViewModelStore we were looking for. The fragment does one thing, and that is execute the ViewModelStore clear method on onDestroy(). And then what does that do? Let’s look at the implementation of the ViewModelStore.

import java.util.HashMap;

/**
 * Class to store {@code ViewModels}.
 * <p>
 * An instance of {@code ViewModelStore} must be retained through configuration changes:
 * if an owner of this {@code ViewModelStore} is destroyed and recreated due to configuration
 * changes, new instance of an owner should still have the same old instance of
 * {@code ViewModelStore}.
 * <p>
 * If an owner of this {@code ViewModelStore} is destroyed and is not going to be recreated,
 * then it should call {@link #clear()} on this {@code ViewModelStore}, so {@code ViewModels} would
 * be notified that they are no longer used.
 * <p>
 * {@link android.arch.lifecycle.ViewModelStores} provides a {@code ViewModelStore} for
 * activities and fragments.
 */
public class ViewModelStore {

    private final HashMap<String, ViewModel> mMap = new HashMap<>();

    final void put(String key, ViewModel viewModel) {
        ViewModel oldViewModel = mMap.get(key);
        if(oldViewModel ! = null) { oldViewModel.onCleared(); } mMap.put(key, viewModel); } final ViewModel get(String key) {return mMap.get(key);
    }

    /**
     *  Clears internal storage and notifies ViewModels that they are no longer used.
     */
    public final void clear() {
        for(ViewModel vm : mMap.values()) { vm.onCleared(); } mMap.clear(); }}Copy the code

I almost forgot, let’s go ahead and insert another code,

import android.annotation.SuppressLint;
import android.app.Application;
import android.support.annotation.NonNull;

/**
 * Application context aware {@link ViewModel}.
 * <p>
 * Subclasses must have a constructor which accepts {@link Application} as the only parameter.
 * <p>
 */
public class AndroidViewModel extends ViewModel {
    @SuppressLint("StaticFieldLeak")
    private Application mApplication;

    public AndroidViewModel(@NonNull Application application) {
        mApplication = application;
    }

    /**
     * Return the application.
     */
    @NonNull
    public <T extends Application> T getApplication() {
        //noinspection unchecked
        return(T) mApplication; }}Copy the code

Our MainModel inherits AndroidViewModel, and AndroidViewModel inherits ViewModel.

This content summed up as one activity holding one

ViewModelStore,
ViewModelStore can hold more than one
ViewModel, and uses a fragment to listen for the activity life cycle, calling all existing fragments when the activity is destroyed

Line — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —

Now that we’re almost halfway there, let’s look at the MutableLiveData class.

@SuppressWarnings("WeakerAccess")
public class MutableLiveData<T> extends LiveData<T> {
    @Override
    public void postValue(T value) {
        super.postValue(value);
    }

    @Override
    public void setValue(T value) { super.setValue(value); }}Copy the code

MutableLiveData inherits the LiveData class, so overwriting these two methods doesn’t work.

/**
 * Posts a task to a main thread to set the given value. So if you have a following code
 * executed in the main thread:
 * <pre class="prettyprint">
 * liveData.postValue("a");
 * liveData.setValue("b");
 * </pre>
 * The value "b" would be set at first and later the main thread would override it with
 * the value "a".
 * <p>
 * If you called this method multiple timesbefore a main thread executed a posted task, only * the last value would be dispatched. * * @param value The new value */ protected void postValue(T value) { boolean  postTask; synchronized (mDataLock) { postTask = mPendingData == NOT_SET; mPendingData = value; }if(! postTask) {return;
    }
    ArchTaskExecutor.getInstance().postToMainThread(mPostValueRunnable);
}

/**
 * Sets the value. If there are active observers, the value will be dispatched to them.
 * <p>
 * This method must be called from the main thread. If you need set a value from a background
 * thread, you can use {@link #postValue(Object)}
 *
 * @param value The new value
 */
@MainThread
protected void setValue(T value) {
    assertMainThread("setValue");
    mVersion++;
    mData = value;
    dispatchingValue(null);
}Copy the code

Good, it’s protected, why didn’t Google just say public in the first place.

Next, analyze this code for the activity:

mMainModel.getMutableLiveData().observe(this, new Observer<String>() { @Override public void onChanged(@Nullable String s) { Toast.makeText(MainActivity.this, s, Toast.LENGTH_SHORT).show(); }});Copy the code

It looks like observer mode. Keep clicking in.

@MainThread
public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<T> observer) {
    if (owner.getLifecycle().getCurrentState() == DESTROYED) {
        // ignore
        return;
    }
    LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer);
    LifecycleBoundObserver existing = mObservers.putIfAbsent(observer, wrapper);
    if(existing ! = null && existing.owner ! = wrapper.owner) { throw new IllegalArgumentException("Cannot add the same observer"
                + " with different lifecycles");
    }
    if(existing ! = null) {return;
    }
    owner.getLifecycle().addObserver(wrapper);
}
Copy the code

LifecycleOwner SupportActivity implements the LifecycleOwner interface by default. Take another look at SupportActivity:

@RestrictTo(LIBRARY_GROUP)
public class SupportActivity extends Activity implements LifecycleOwner {
    /**
     * Storage for{@link ExtraData} instances. * * <p>Note that these objects are not retained across configuration changes</p> */ private  SimpleArrayMap<Class<? extends ExtraData>, ExtraData> mExtraDataMap = new SimpleArrayMap<>(); private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this); /** * Store an instance of {@link ExtraData}for later retrieval by class name
     * via {@link #getExtraData}.
     *
     * <p>Note that these objects are not retained across configuration changes</p>
     *
     * @see #getExtraData
     * @hide
     */
    @RestrictTo(LIBRARY_GROUP)
    public void putExtraData(ExtraData extraData) {
        mExtraDataMap.put(extraData.getClass(), extraData);
    }

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

    @CallSuper
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        mLifecycleRegistry.markState(Lifecycle.State.CREATED);
        super.onSaveInstanceState(outState);
    }

    /**
     * Retrieves a previously set {@link ExtraData} by class name.
     *
     * @see #putExtraData
     * @hide
     */
    @RestrictTo(LIBRARY_GROUP)
    public <T extends ExtraData> T getExtraData(Class<T> extraDataClass) {
        return (T) mExtraDataMap.get(extraDataClass);
    }

    @Override
    public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }

    /**
     * @hide
     */
    @RestrictTo(LIBRARY_GROUP)
    public static class ExtraData {
    }
}
Copy the code

LifecycleRegistry is a fragment that detects the activity lifecycle. Looking directly at the code doesn’t seem to reveal much. Since the life cycle, let’s start with the onCreate method:

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

Good, another one that looks like a Fragment. Click on it.

public static void injectIfNeededIn(Activity activity) {
    // ProcessLifecycleOwner should always correctly work and some activities may not extend
    // FragmentActivity from support lib, so we use framework fragments for activities
    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(); }}Copy the code

A fragment is added to the activity.

@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) lifecycle).handleLifecycleEvent(event); }}}Copy the code

Each lifecycle calls the Dispatch method, and then look at the implementation of dispatch and see what methods are in our LifecycleRegistry:

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;
}
Copy the code

LifecycleRegistry is completely dependent on the activity lifecycle, since we only care about the mState.

Back to the original code:

@MainThread
public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<T> observer) {
    if (owner.getLifecycle().getCurrentState() == DESTROYED) {
        // ignore
        return;
    }
    LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer);
    LifecycleBoundObserver existing = mObservers.putIfAbsent(observer, wrapper);
    if(existing ! = null && existing.owner ! = wrapper.owner) { throw new IllegalArgumentException("Cannot add the same observer"
                + " with different lifecycles");
    }
    if(existing ! = null) {return;
    }
    owner.getLifecycle().addObserver(wrapper);
}Copy the code

LifecyclerBoundObserver

class LifecycleBoundObserver implements GenericLifecycleObserver {
    public final LifecycleOwner owner;
    public final Observer<T> observer;
    public boolean active;
    public int lastVersion = START_VERSION;

    LifecycleBoundObserver(LifecycleOwner owner, Observer<T> observer) {
        this.owner = owner;
        this.observer = observer;
    }

    @Override
    public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
        if (owner.getLifecycle().getCurrentState() == DESTROYED) {
            removeObserver(observer);
            return;
        }
        // immediately set active state, so we'd never dispatch anything to inactive // owner activeStateChanged(isActiveState(owner.getLifecycle().getCurrentState())); } void activeStateChanged(boolean newActive) { if (newActive == active) { return; } active = newActive; boolean wasInactive = LiveData.this.mActiveCount == 0; LiveData.this.mActiveCount += active ? 1:1; if (wasInactive && active) { onActive(); } if (LiveData.this.mActiveCount == 0 && ! active) { onInactive(); } if (active) { dispatchingValue(this); } } } static boolean isActiveState(State state) { return state.isAtLeast(STARTED); }public boolean isAtLeast(@NonNull State state) { return compareTo(state) >= 0; }Copy the code

This code will call LiveData onActive(), onInactive(), dispatchingValue () depending on the state.

Methods.

MObservers stores the LifecycleBoundObserver and iterates through the dispatchingValue method to retrieve all observers and call the onChange method.

The setValue code

@MainThread
protected void setValue(T value) {
    assertMainThread("setValue");
    mVersion++;
    mData = value;
    dispatchingValue(null);
}

private void dispatchingValue(@Nullable LifecycleBoundObserver initiator) {
    if (mDispatchingValue) {
        mDispatchInvalidated = true;
        return;
    }
    mDispatchingValue = true;
    do {
        mDispatchInvalidated = false;
        if(initiator ! = null) { considerNotify(initiator); initiator = null; }else {
            for (Iterator<Map.Entry<Observer<T>, LifecycleBoundObserver>> iterator =
                    mObservers.iteratorWithAdditions(); iterator.hasNext(); ) {
                considerNotify(iterator.next().getValue());
                if (mDispatchInvalidated) {
                    break; }}}}while (mDispatchInvalidated);
    mDispatchingValue = false;
}

private void considerNotify(LifecycleBoundObserver observer) {
    if(! observer.active) {return;
    }
    // Check latest state b4 dispatch. Maybe it changed state but we didn't get the event yet. // // we still first check observer.active to keep it as the entrance for events. So even if // the observer moved to an active state, if we've not received that event, we better not
    // notify for a more predictable notification order.
    if(! isActiveState(observer.owner.getLifecycle().getCurrentState())) { observer.activeStateChanged(false);
        return;
    }
    if (observer.lastVersion >= mVersion) {
        return;
    }
    observer.lastVersion = mVersion;
    //noinspection unchecked
    observer.observer.onChanged((T) mData);
}

Copy the code

The next step is to determine the active, which is the LifecycleBoundObserver active, and finally call the corresponding observer onChange method,

Almost the main process has been analyzed, because my Android level is general, it is the first time to write an article, so there must be a lot of misunderstanding in the article, I hope you can give me advice, learn together, progress together