4. Jetpack源码解析—LiveData的使用及工做原理

1. 背景

上一篇咱们分析了Lifecycles组件的源码,本篇咱们将继续分析LiveData组件java

相关系列文章:git

1. Jetpack源码解析---看完你就知道Navigation是什么了?github

2. Jetpack源码解析---Navigation为何切换Fragment会重绘?app

3. Jetpack源码解析---用Lifecycles管理生命周期异步

2. 基础

2.1 简介

LiveData是一个可观察的数据持有者类,与常规observable不一样,LiveData是生命周期感知的,这意味着它尊重其余应用程序组件的生命周期,例如ActivityFragmentService。此感知确保LiveData仅更新处于活动生命周期状态的应用程序组件观察者。ide

2.2 优势

1. 确保UI符合数据状态 LiveData遵循观察者模式。 当生命周期状态改变时,LiveData会向Observer发出通知。 您能够把更新UI的代码合并在这些Observer对象中。没必要去考虑致使数据变化的各个时机,每次数据有变化,Observer都会去更新UI。函数

2. 没有内存泄漏 Observer会绑定具备生命周期的对象,并在这个绑定的对象被销毁后自行清理。源码分析

3. 不会因中止Activity而发生崩溃 若是Observer的生命周期处于非活跃状态,例如在后退堆栈中的Activity,就不会收到任何LiveData事件的通知。post

4.不须要手动处理生命周期 UI组件只须要去观察相关数据,不须要手动去中止或恢复观察。LiveData会进行自动管理这些事情,由于在观察时,它会感知到相应组件的生命周期变化。ui

5. 始终保持最新的数据 若是一个对象的生命周期变到非活跃状态,它将在再次变为活跃状态时接收最新的数据。 例如,后台Activity在返回到前台后当即收到最新数据。

6. 正确应对配置更改 若是一个Activity或Fragment因为配置更改(如设备旋转)而从新建立,它会当即收到最新的可用数据。

7.共享资源 您可使用单例模式扩展LiveData对象并包装成系统服务,以便在应用程序中进行共享。LiveData对象一旦链接到系统服务,任何须要该资源的Observer都只需观察这个LiveData对象。

2.3 基本使用

在咱们的Jetpack_Note中有使用demo,具体可查看LiveDataFragment。 Demo中经过对一个LiveData对象进行生命周期的监听,实现将值打印在控制台中。首先声明一个LiveData对象:

private lateinit var liveData: MutableLiveData<String>
复制代码

点击开始观察数据按钮,弹出控制台,咱们能够看到控制台输出了onStart()日志,由于咱们将liveData的值和Fragment的生命周期进行了绑定,当返回桌面或者销毁Fragment的时候,LiveData的值会变成相应的生命周期函数,并打印在控制台中:

class LiveDataFragment : Fragment() {

    private lateinit var liveData: MutableLiveData<String>

    override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? {
        return inflater.inflate(R.layout.fragment_live_data, container, false)
    }


    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        liveData = MutableLiveData()
        btn_observer_data.setOnClickListener {
            if (FloatWindow.get() == null) {
                FloatWindowUtils.init(activity?.application!!)
            }
            FloatWindowUtils.show()

            //建立一个观察者去更新UI
            val statusObserver = Observer<String> { lifeStatus ->
                FloatWindowUtils.addViewContent("LiveData-onChanged: $lifeStatus")
            }
            liveData.observeForever(statusObserver)
        }
    }


    override fun onStart() {
        super.onStart()
        liveData.value = "onStart()"
    }


    override fun onPause() {
        super.onPause()
        liveData.value = "onPause()"
    }

    override fun onStop() {
        super.onStop()
        liveData.value = "onStop()"
    }

    override fun onDestroy() {
        super.onDestroy()
        liveData.value = "onDestroy()"
    }
}
复制代码

**注意:**这里我使用了observeForever监听了全部生命周期方法,因此你会看到onDestroy()等生命周期函数的打印。

好了,Demo很简单,接下来咱们来看一下源码,进行分析:

3. 源码分析:

3.1 observer()

咱们声明了一个LiveData对象,并经过监听Fragment的生命周期来改变LiveData中的value值,LiveData实际上就像一个容器,Demo中存储了一个String类型的值,当这个值发生改变的时候,能够在回调中监听到他的改变。接下来咱们就先从addObserver入手:

@MainThread
    public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<? super T> observer) {
        assertMainThread("observe");
        if (owner.getLifecycle().getCurrentState() == DESTROYED) {
            // ignore
            return;
        }
        LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, 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);
    }
复制代码

查看源码,咱们调用observer()时,传递了两个参数,第一个是LifecycleOwner接口实例,而咱们继承的Fragment自己就已经实现了这个接口,因此咱们传this便可;第二个参数Observer就是咱们观察的回调。接下来将这两个参数传递new出了一个新的对象:LifecycleBoundObserver,最后将LifecycleBoundObserverLifecycleOwner进行了绑定,其实这里面咱们能够将LifecycleOwner就理解成咱们的Fragment或者Activity的实例,由于它们都实现了LifecycleOwner

3.2 LifecycleBoundObserver

class LifecycleBoundObserver extends ObserverWrapper implements GenericLifecycleObserver {
        .....
        @Override
        boolean shouldBeActive() {
            return mOwner.getLifecycle().getCurrentState().isAtLeast(STARTED);
        }
        //Activity生命周期变化时,回调方法
        @Override
        public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
            if (mOwner.getLifecycle().getCurrentState() == DESTROYED) {
                removeObserver(mObserver);
                return;
            }
            //更新livedata活跃状态
            activeStateChanged(shouldBeActive());
        }

        @Override
        boolean isAttachedTo(LifecycleOwner owner) {
            return mOwner == owner;
        }
        //解除监听
        @Override
        void detachObserver() {
            mOwner.getLifecycle().removeObserver(this);
        }
    }
复制代码

咱们能够看到这里面与LifecycleOwner进行了绑定,而且实现了onStateChanged方法,当生命周期发生变化时执行activeStateChanged(shouldBeActive());方法;shouldBeActive() 返回了 要求生命周期至少是STARTED状态才被认为是activie状态;若是state是DESTROYED状态时,解绑LifecycleOwnerLiveData。接下来咱们看下怎样更新livedata中数据值:

3.3 dispatchingValue()

咱们追踪activeStateChanged方法发现,在里面作了一些活跃状态值的操做,而且当状态活跃时,更新数据值:

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;
            if (wasInactive && mActive) {
                onActive();
            }
            if (LiveData.this.mActiveCount == 0 && !mActive) {
                onInactive();
            }
            if (mActive) {
                dispatchingValue(this);
            }
        }
复制代码
void dispatchingValue(@Nullable ObserverWrapper initiator) {
    ...
    //遍历LiveData的全部观察者执行下面代码
    for (Iterator<Map.Entry<Observer<? super T>, ObserverWrapper>> iterator =
                        mObservers.iteratorWithAdditions(); iterator.hasNext(); ) {
                    considerNotify(iterator.next().getValue());
                    if (mDispatchInvalidated) {
                        break;
                    }
                }
    ...
}
//将数据值回调到livedata.observer()回去
private void considerNotify(ObserverWrapper observer) {
        if (!observer.mActive) {
            return;
        }
        if (!observer.shouldBeActive()) {
            observer.activeStateChanged(false);
            return;
        }
        if (observer.mLastVersion >= mVersion) {
            return;
        }
        observer.mLastVersion = mVersion;
        observer.mObserver.onChanged((T) mData);
    }
复制代码

从上面咱们能够看到LiveData的数据更新以及数据回调的整个过程,可是当咱们手动setValue()的时候过程是怎样的呢?你会发现,setValue()其实最后就是经过调用了dispatchingValue()方法。而关于postValue()在子线程更新数据的相关代码,这里就不作介绍了,其实你大能够想出来,就是使用的Handler

LiveData中的代码很简洁,400多行的代码,看起来也并不费劲,下面咱们来分析下整个流程:

  • 经过使用LiveData对象,为它建立观察者Observer
  • 建立Observer时绑定Fragment生命周期
  • LifecycleBoundObserver生命周期变化时,dispatchValue下发更新LiveData中的值
  • LiveData主动setValue时,会主动dispatchValue,而且会considerNotify激活observer

4. 扩展

4.1 Map转换

咱们在开发中常常会遇到这种场景,有时咱们须要根据另一个LiveData实例返不一样的LiveData实例,而后在分发给Observer,Lifecycle包提供了Transformations类,能够帮助咱们实现这样的场景:

经过**Transformations.map()**使用一个函数来转换存储在 LiveData对象中的值,并向下传递转换后的值:

LiveDataViewModel

class LiveDataViewModel : ViewModel() {
    val data = listOf(User(0,"Hankkin"), User(1,"Tony"),User(2,"Bob"),User(3,"Lucy"))

    val id = MutableLiveData<Int>()
    //map转换返回User实体
    val bean: LiveData<User> = Transformations.map(id, Function {
        return@Function findUserById(id.value!!)
    })
    //根据id查找User
    private fun findUserById(id: Int): User? {
        return data.find { it.id == id }
    }
}
复制代码

LiveDataFragment

//改变ViewModel中idLiveData中的值
        btn_observer_map.setOnClickListener {
            mId++
            viewModel.id.postValue(mId)
        }
        //当idLiveData变化后,UserBean也会改变且更新Textview的文本
        viewModel.bean.observe(
            this,
            Observer { tv_livedata_map.text = if (it == null) "未查找到User" else "为你查找到的User为:${it.name}" })
复制代码

4.2 Map源码

@MainThread
    public static <X, Y> LiveData<Y> map( @NonNull LiveData<X> source, @NonNull final Function<X, Y> mapFunction) {
        final MediatorLiveData<Y> result = new MediatorLiveData<>();
        result.addSource(source, new Observer<X>() {
            @Override
            public void onChanged(@Nullable X x) {
                result.setValue(mapFunction.apply(x));
            }
        });
        return result;
    }
复制代码

咱们能够看到map的源码是经过MediatorLiveData中的addSource()方法来实现的,第一个参数为咱们须要改变的LiveData值,也就是咱们上面例子中的userid,第二个参数则是咱们传过来的Fuction经过高阶函数,将值set到LiveData上。

下面咱们看下addSource()方法:

@MainThread
    public <S> void addSource(@NonNull LiveData<S> source, @NonNull Observer<? super S> onChanged) {
        Source<S> e = new Source<>(source, onChanged);
        Source<?> existing = mSources.putIfAbsent(source, e);
        if (existing != null && existing.mObserver != onChanged) {
            throw new IllegalArgumentException(
                    "This source was already added with the different observer");
        }
        if (existing != null) {
            return;
        }
        if (hasActiveObservers()) {
            e.plug();
        }
    }
复制代码

这里把咱们的LiveData和Observer封装成了Source对象,而且这个对象,不能重复添加,具体代码可查看Source:

private static class Source<V> implements Observer<V> {
        final LiveData<V> mLiveData;
        final Observer<? super V> mObserver;
        int mVersion = START_VERSION;

        Source(LiveData<V> liveData, final Observer<? super V> observer) {
            mLiveData = liveData;
            mObserver = observer;
        }

        void plug() {
            mLiveData.observeForever(this);
        }

        void unplug() {
            mLiveData.removeObserver(this);
        }

        @Override
        public void onChanged(@Nullable V v) {
            if (mVersion != mLiveData.getVersion()) {
                mVersion = mLiveData.getVersion();
                mObserver.onChanged(v);
            }
        }
    }
复制代码

首先Source是一个观察者,能够看到,咱们外部使用的Observer会以Source的成员变量的形式,添加到传入的LiveData中。值得注意的是,这里使用了mLiveData.observeForever(this);

observeForever()用法能够看到,咱们并无传递LifecycleOwner,所以它并不具有生命感知能力。从注释中也可见一斑:This means that the given observer will receive all events and will never be automatically removed.

map()的原理就是基于MediatorLiveData,MediatorLiveData内部会将传递进来的LiveData和Observer封装成内部类,而后放在内部维护的一个Map中。而且自动帮咱们完成observeForever()和removeObserver()

5.总结

  • LiveData基于观察者模式实现,而且和LifecycleOwner进行绑定,而LifecycleOwner又被Fragment和Activity实现,因此它能够感知生命周期;在当前的LifecycleOwner不处于活动状态(例如onPasue()onStop())时,LiveData是不会回调observe()的,由于没有意义.
  • 同时LiveData只会在LifecycleOwner处于Active的状态下通知数据改变,果数据改变发生在非 active 状态,数据会变化,可是不发送通知,等 owner 回到 active 的状态下,再发送通知;
  • LiveData在DESTROYED时会移除Observer,取消订阅,不会出现内存泄漏
  • postValue在异步线程,setValue在主线程
  • 若是LiveData没有被observe(),那么此时你调用这个LiveData的postValue(...)/value=...,是没有任何做用

固然官方推荐咱们LiveData配合ViewModel一块儿使用,由于LiveData通常都出如今ViewModel中,因此咱们下篇文章会继续分析ViewModel.

相关文章
相关标签/搜索