Android Architecture Component 原始碼淺析

順其自然55發表於2017-11-09
首先放上官方文件地址,eveloper.android.google.cn/topic/libra…

直接進入正題,首先新建專案,預設整合v7包(版本大於26.1.0),這時候看整體依賴,

Android Architecture Component 原始碼淺析

未整合lifecycler的包,但是預設卻有了。這時候我們再看看activity和fragment。

Android Architecture Component 原始碼淺析

Android Architecture Component 原始碼淺析

v4的SupportActivity和Fragment預設實現了LifecycleOwner介面,看來谷歌已經讓v4預設依賴licfcycle,我們繼續。

再在主build.gradle中新增如下:

allprojects{  repositories{      jcenter()      maven{url'https://maven.google.com'
}}複製程式碼

然後在app的build.gradle中新增如下:

implementation "android.arch.lifecycle:extensions:1.0.0"
annotationProcessor "android.arch.lifecycle:compiler:1.0.0"複製程式碼

編譯完成,開始寫一點簡單的程式碼(用法就不講了,這節主要講一些原始碼,具體用法可以看看官方文件,還有很多優秀的部落格)。

首先寫個資料類:

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() {
        return mMutableLiveData;
    }

    /**
     * 模仿獲取資料.
     */
    public void requestGetData() {
        try {
            Thread.sleep(1000);
            getMutableLiveData().setValue("獲取的資料");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
@Override
protected void onCleared() {
    Log.d("MainModel", "清除資源");
}}
複製程式碼

然後時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();
            }
        });
    }
}複製程式碼

功能很簡單,就是點選按鈕,假設獲取資料,然後獲取資料後打toast.

現在開始簡單分析原始碼,首先從activity入手,看這行程式碼:

 mMainModel = ViewModelProviders.of(this).get(MainModel.class);複製程式碼

看谷歌給的用法就是這個,好奇為啥不直接new出來,一看class,就想起來反射。

首先of方法點進去檢視,

@MainThread
public static ViewModelProvider of(@NonNull FragmentActivity activity) {

    //這句話是建立了sDefaultFactory物件
    initializeFactoryIfNeeded(checkApplication(activity));

    return new ViewModelProvider(ViewModelStores.of(activity), sDefaultFactory);
}

public ViewModelProvider(@NonNull ViewModelStore store, @NonNull Factory factory) {
    mFactory = factory;
    this.mViewModelStore = store;
}

/**
*這個factory只有一個通過反射建立物件(持有application引用)
*/@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);
            }
        }
        return super.create(modelClass);
    }
}
複製程式碼

of還有個方法是這個,就是自己繼承ViewModelProvider.NewInstanceFactory,實現create方法,返回自己想要物件。

@MainThread
public static ViewModelProvider of(@NonNull Fragment fragment, @NonNull Factory factory) {
    checkApplication(checkActivity(fragment));
    return new ViewModelProvider(ViewModelStores.of(fragment), factory);
}複製程式碼

至於接下來的ViewModelProviders.of(this).get(MainModel.class)的get方法就簡單了,直接呼叫預設或者自己整合的factory的create方法,同時又將這個viewModel put到mViewModelStore裡,至於mViewModelStore是啥,幹嘛用,繼續來分析。

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

複製程式碼

首先繼續回到ViewModelProviders的of方法上

@MainThread
public static ViewModelProvider of(@NonNull FragmentActivity activity) {
    initializeFactoryIfNeeded(checkApplication(activity));
    return new ViewModelProvider(ViewModelStores.of(activity), sDefaultFactory);
}複製程式碼

接下來將看ViewModelStores.of(activity)這個,mViewModelStore引用的就是ViewModelStores.of(activity)返回的物件。這個類很簡單:

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 a {@code ViewModelStore}
     */就是這句話
    @MainThread
    public static ViewModelStore of(@NonNull FragmentActivity activity) {
        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) {
        return holderFragmentFor(fragment).getViewModelStore();
    }
}
複製程式碼

現在只先看activity相關的,所以繼續看holderFragmentFor(activity).getViewModelStore();

接下來追蹤程式碼:

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

/**
 * @hide
 */
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public static HolderFragment holderFragmentFor(FragmentActivity activity) {
    return sHolderFragmentManager.holderFragmentFor(activity);
}

/**
 * 主要程式碼
 */
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;
}

複製程式碼

就到這裡了,已經開始有點眉目了,HolderFragment是一個Fragment. 首先從當前的activity的FragmentManager找尋當前的holderFragment,activity中程式碼第一次執行到這裡,肯定是空的,所以繼續從mNotCommittedActivityHolders找當,mNotCommittedActivityHolders是一個hashmap,當然也是空的,所以接下來呼叫application執行activity的生命週期處理,registerActivityLifecycleCallbacks,如果這個不知道的話,那你該惡補下基礎知識了。

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);
                }
            }
        };
複製程式碼

就是在activity銷燬時候移除當前fragment,再接下來程式碼就是往當前activity新增當前的fragment,將activity作為key新增當前fragment。接下來看看HolderFragment到底幹了什麼事了。

/**
 * @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;
    }
複製程式碼

 HolderFragment中有個ViewModelStore,這就是我們之前要找的mViewModelStore,fragment的作用只做了一件事,那就是在onDestroy()時候執行了ViewModelStore的clear方法。然後這有什麼用呢,我們來看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();
    }
}複製程式碼

差點忘記了,繼續插一段程式碼,

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;
    }
}
複製程式碼

我們的MainModel繼承了AndroidViewModel,而AndroidViewModel繼承了ViewModel。

這個內容總結起來就是一個activity持有一個
ViewModelStore,而ViewModelStore中可以存放多個ViewModel,並且使用了一個fragment監聽activity生命週期,在activity被銷燬時呼叫所有存於 ViewModelStore中的ViewModel的clear方法。

分割線-------------------------------------------------------------------------------------------------

到這裡我們已經差不多搞懂了一半,接下來我們分析MutableLiveData這個類。

@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);
    }
}
複製程式碼

這裡MutableLiveData繼承了LiveData這個類,重寫這兩個方法貌似沒啥用啊,為啥呢,來看LiveData:

/**
 * 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 times before 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);
}複製程式碼

很好,是protected的,為啥谷歌不一開始就寫成public呢。 

接下來分析activity的這段程式碼:

mMainModel.getMutableLiveData().observe(this, new Observer<String>() {
    @Override
    public void onChanged(@Nullable String s) {
        Toast.makeText(MainActivity.this, s, Toast.LENGTH_SHORT).show();
    }
});複製程式碼

一看就是觀察者模式嘛。繼續點進去。

@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);
}
複製程式碼

看第一句話意思是被銷燬後,就return不繼續執行了,LifecycleOwner前面已經看到過了,SupportActivity預設已經實現了LifecycleOwner的介面。再看一下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 {
    }
}
複製程式碼

看到關鍵點LifecycleRegistry,但是好像就沒做其他事了,它事怎麼監聽到activity生命週期呢,難道也是用fragment?直接看程式碼好像也沒啥發現,既然生命週期,那就從onCreate方法開始吧:

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

很好,又發現一個看上去根本就是Fragment的傢伙,點進去看看。

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();
    }
}複製程式碼

發現了,又是新增進activity的fragment,趕快看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) lifecycle).handleLifecycleEvent(event);
        }
    }
}
複製程式碼

每個生命週期裡都呼叫了dispatch方法,然後看dispatch的實現,再看我們的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;
}
複製程式碼

我們只關注mState的狀態,這下子LifecycleRegistry可是完全跟著activity的生命週期變化了。

回到原先程式碼:

@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);
}複製程式碼

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;
}
複製程式碼

這個程式碼會根據不同的狀態去呼叫LiveData的 onActive(),onInactive(),dispatchingValue()

方法。

mObservers將LifecycleBoundObserver存進去,在dispatchingValue方法中通過迭代會將所有的觀察者取出來,呼叫onChange方法。

看setValue程式碼

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

複製程式碼

接下來就是判斷active,就是上面的LifecycleBoundObserver的active,最後呼叫對應的observer的onChange方法,

差不多主要流程已經分析完了,由於本人安卓水平一般,也是第一次寫文章,所以文中肯定也有不少理解錯的地方,希望各位能指教,一起學習,一起進步


相關文章