Jetpack -- LiveData使用与源码流程分析

简介

  • LiveData是给定生命周期的一个数据持有类
  • LiveData配合ViewModel可以将Controller中的逻辑更加简单,在数据进行变动的时候可以通过注入观察者来监听数据的变化
  • LiveData可以感知实现LifecycleOwner组件的生命周期,只有在上述组件的激活状态 (STARTED, RESUMED) 才会通知观察者数据更新
  • 当组件的生命周期到了DESTROYED状态的时候,添加的观察者将会被自动移除

使用示例

  • 配合ViewModel使用
class MyViewModel : ViewModel() {
    // MutableLiveData 是 LiveData 的一个最简单实现,它可以接收数据更新并通知观察者
    private var mLikedNumber: MutableLiveData? = null


    fun getLikedNumber(): MutableLiveData {
        if (mLikedNumber == null) {
            mLikedNumber = MutableLiveData()
            mLikedNumber!!.value = 0
        }
        return mLikedNumber!!
    }


    fun setLikedNumber(value: Int) {
        mLikedNumber!!.value = mLikedNumber!!.value!! + value
    }
}
class MainActivity : AppCompatActivity() {
    var mViewModel: MyViewModel? = null
    private lateinit var activityMainBinding: ActivityMainBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main2)
        // ViewModel和控制器绑定
        mViewModel = ViewModelProviders.of(this).get(MyViewModel::class.java)
        // 给LiveData设置一个观察者,观察数据的变化,数据发生变化,就直接更新到View之上
        mViewModel!!.getLikedNumber().observe(this, Observer {integer ->
            integer?.let {
                textView.setText(integer.toString())
            }
        })
        button.setOnClickListener({
            mViewModel!!.setLikedNumber(1)
        })
        button2.setOnClickListener({
            mViewModel!!.setLikedNumber(2)
        })
    }
}

实际应用

  • 我们一般可以定义一个Repository负责从网络或者数据库中获取数据,下面是数据的处理链以及实际应用实现(具体代码可以参考)
  • Jetpack -- LiveData使用与源码流程分析_第1张图片
//  Repository
class HomeRepository (loadState : MutableLiveData) : BaseArticleRepository(loadState) {
    fun loadBanner(liveData: MutableLiveData>>) {
        apiService.loadBanner()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(BaseObserver(liveData, loadState, this))
    }


    fun loadHomeArticle(pageNum : Int, liveData: MutableLiveData>) {
        apiService.loadHomeArticle(pageNum)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(BaseObserver(liveData, loadState, this))
    }


    fun loadTopArticle(liveData: MutableLiveData>>) {
        apiService.loadTopArticle()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(BaseObserver(liveData, loadState, this))
    }
}

//  ViewModel
class HomeViewModel(application: Application) :
    BaseArticleViewModel(application) {
    val mBannerData : MutableLiveData>> = MutableLiveData()
    val mHomeArticleData : MutableLiveData> = MutableLiveData()
    val mTopArticleData : MutableLiveData>> = MutableLiveData()


    fun loadBanner() {
        mRepository.loadBanner(mBannerData)
    }


    fun loadHomeArticleData(pageNum : Int) {
        mRepository.loadHomeArticle(pageNum, mHomeArticleData)
    }


    fun loadTopArticle() {
        mRepository.loadTopArticle(mTopArticleData)
    }
}

// View
mViewModel.mBannerData.observe(this, Observer { response ->
    response?.let {
        setBannerData(it.data)
    }
})

实现原理

  • 了解了如何使用LiveData,那么就从源码的角度对LiveData的观察者模式进行解读,对其再进行深入的理解
添加观察者的方法observe说起
@MainThread
public void observe(@NonNull LifecycleOwner owner, @NonNull Observer observer) {
    assertMainThread("observe");
    if (owner.getLifecycle().getCurrentState() == DESTROYED) {
        // ignore
        return;
    }
    // 将LifecycleOwner对象(Activity, Fragment, Service)封装成LifecycleBoundObserver对象
    LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer);
    // 对observer的唯一性进行判断
    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.getLifecycle().addObserver(wrapper);
}

上面看到如果当前组件处于非DESTROYED状态就会封装成LifecycleBoundObserver

class LifecycleBoundObserver extends ObserverWrapper implements LifecycleEventObserver {
    @NonNull
    final LifecycleOwner mOwner;


    LifecycleBoundObserver(@NonNull LifecycleOwner owner, Observer observer) {
        super(observer);
        mOwner = owner;
    }


    @Override
    boolean shouldBeActive() {
        return mOwner.getLifecycle().getCurrentState().isAtLeast(STARTED);
    }


        // 组件生命周期发生改变的回调方法
    @Override
    public void onStateChanged(@NonNull LifecycleOwner source,
            @NonNull Lifecycle.Event event) {
        // 如果是DESTROYED状态则移除观察者
        if (mOwner.getLifecycle().getCurrentState() == DESTROYED) {
            removeObserver(mObserver);
            return;
        }
        // 将状态传入activeStateChanged
        activeStateChanged(shouldBeActive());
    }


    @Override
    boolean isAttachedTo(LifecycleOwner owner) {
        return mOwner == owner;
    }


    @Override
    void detachObserver() {
        mOwner.getLifecycle().removeObserver(this);
    }
}

void activeStateChanged(boolean newActive) {
    // 状态不发生改变不做处理
    if (newActive == mActive) {
        return;
    }
    // immediately set active state, so we'd never dispatch anything to inactive
    // owner
    mActive = newActive;
    boolean wasInactive = LiveData.this.mActiveCount == 0;
    LiveData.this.mActiveCount += mActive ? 1 : -1;
    // 分别对是否在激活状态的observer个数进行+1, -1
    if (wasInactive && mActive) {
        onActive(); // +1 使得 从0->1 添加观察者
    }
    if (LiveData.this.mActiveCount == 0 && !mActive) {
        onInactive();// -1使得从1->0 移除观察者
    }
    if (mActive) {
        dispatchingValue(this);
    }
}
dispatchingValue

void dispatchingValue(@Nullable ObserverWrapper initiator) {
    if (mDispatchingValue) {
        mDispatchInvalidated = true;
        return;
    }
    mDispatchingValue = true;
    do {
        mDispatchInvalidated = false;
        if (initiator != null) {
            // 如果observer不为空,通知回调
            considerNotify(initiator);
            initiator = null;
        } else {
            // observer为空,则将mObservers容器中的值进行遍历调用,将数据分发给各个观察者
            for (Iterator, ObserverWrapper>> iterator =
                    mObservers.iteratorWithAdditions(); iterator.hasNext(); ) {
                considerNotify(iterator.next().getValue());
                if (mDispatchInvalidated) {
                    break;
                }
            }
        }
    } while (mDispatchInvalidated);
    mDispatchingValue = false;
}

private void considerNotify(ObserverWrapper observer) {
    if (!observer.mActive) {
        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 (!observer.shouldBeActive()) {
        observer.activeStateChanged(false);
        return;
    }
    if (observer.mLastVersion >= mVersion) {
        return;
    }
    observer.mLastVersion = mVersion;
        //  回调可观察对象的onChange()方法即我们在View中重写的方法
    observer.mObserver.onChanged((T) mData);
}

整个分析流程如下

你可能感兴趣的:(Android源码分析,Android项目,Kotlin,Android,android)