Android官方架構元件之LiveData + ViewModel + Room 原始碼分析一

weixin_34337265發表於2018-05-23

簡單使用案例:
MainActivity:

viewModel.getMessageObserver().observe(this, new Observer<MessageBean>() {
    @Override
    public void onChanged(@Nullable MessageBean messageBean) {
        if (messageBean != null) {
            LogUtils.d(messageBean.toString());
        }
    }
});

MessageViewModel:

public class MessageViewModel extends ViewModel {

    private final MutableLiveData<MessageBean> mMessageObserver = new MutableLiveData<>();

    public LiveData<MessageBean> getMessageObserver() {
        return mMessageObserver ;
    }

    public void setHoroscopeId(int horoscopeId) {
        List<MessageBean> characters = new ArrayList<>();
        characters.add(new MessageBean("body1"));
        characters.add(new MessageBean("body2"));
        characters.add(new MessageBean("body3"));
        characters.add(new MessageBean("body4"));

        mMessageObserver.setValue(characters.get(horoscopeId));
    }

    public void getProjectList() {
        DataRepository.getInstance().getProjectList(mMessageObserver , "1", 294);
    }
}

其中viewModel.getMessageObserver().observe(this, new Observer() )
中的this即SupportActivity :LifecycleOwner

SupportActivity implements LifecycleOwner

public interface LifecycleOwner {
    Lifecycle getLifecycle();
}

SupportActivity

public class SupportActivity extends Activity implements LifecycleOwner {

    private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);

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

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

SupportActivity就是通過getLifecycle()獲取 mLifecycleRegistry來標記當前Activity或Fragment的各種狀態,其中ReportFragment.injectIfNeededIn(this)內部原始碼也是與mLifecycleRegistry.markState(Lifecycle.State.CREATED) 類似,狀態的資訊記錄在mLifecycleRegistry物件內部。Activity的其他型別的事件如onCreate,onPause等都是通過getLifecycle()獲取 mLifecycleRegistry物件呼叫mLifecycleRegistry內部方法來改變其狀態的。

Fragment的狀態更加容易看到,FragmentActivity即在Activity的生命週期中獲取

FragmentActivity部分原始碼:

    @Override
    protected void onStop() {
        super.onStop();

        mStopped = true;
        markState(getSupportFragmentManager(), Lifecycle.State.CREATED);
        mHandler.sendEmptyMessage(MSG_REALLY_STOPPED);

        mFragments.dispatchStop();
    }

    private static void markState(FragmentManager manager, Lifecycle.State state) {
        Collection<Fragment> fragments = manager.getFragments();
        for (Fragment fragment : fragments) {
            if (fragment == null) {
                continue;
            }
            fragment.mLifecycleRegistry.markState(state);
            markState(fragment.getChildFragmentManager(), state);
        }
    }

通過上面的簡單分析,兩個重要的類即 LifecycleRegistry extends Lifecycle:

下面是Lifecycle抽象類:

public abstract class Lifecycle {
  
    @MainThread
    public abstract void addObserver(@NonNull LifecycleObserver observer);

  
    @MainThread
    public abstract void removeObserver(@NonNull LifecycleObserver observer);

    @MainThread
    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,

        INITIALIZED,

        CREATED,

        STARTED,

        RESUMED;

        public boolean isAtLeast(@NonNull State state) {
            return compareTo(state) >= 0;
        }
    }
}

回到開始的案例:
LiveData.observe(this, new Observer);

    public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<T> observer) {
        if (owner.getLifecycle().getCurrentState() == DESTROYED) {
            // ignore
            return;
        }
        // 經典的裝飾器模式,這裡的設計很精妙,可以看出我們傳入的Observer和 owner.getLifecycle().addObserver()是不同的。
        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);
    }

這裡我們傳入的Observer和 owner.getLifecycle().addObserver()即 Activity中的Lifecycle 是不同的。
我們上面已經知道Activity中的Lifecycle是與生命週期相關的,通過Lifecycle.addObserver()可以監聽到 Activity的生命週期 然後在LifecycleBoundObserver作出
相應的處理,具體的實現在LifecycleRegistry.addObserver中(Lifecycle實現類),最終會根據事件變化呼叫 mLifecycleObserver.onStateChanged(owner, event),

class LifecycleBoundObserver implements GenericLifecycleObserver {
    public final LifecycleOwner owner;
    public final Observer<T> observer;

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

    @Override
    public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
        // 此處在元件如Activity onDestroy的時候自動移除觀察者。
        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()));
    }
}

LifecycleBoundObserver.onStateChanged -> activeStateChanged -> dispatchingValue -> considerNotify(initiator) -> observer.observer.onChanged((T) mData);

最終呼叫的是我們傳入的observer。

這樣看來 LiveData<T> 就沒有什麼特殊的了,把它看做一個普通的觀察者模式的管理者即可,比如EventBus。

public abstract class LiveData<T> {
    
    private static final Object NOT_SET = new Object();
    
    // LiveData<T> 存取的值,即T, setValue,postValue 會強制轉換為T。    
    private volatile Object mData = NOT_SET;
}

https://developer.android.com/reference/android/arch/lifecycle/Lifecycle

相關文章