美文网首页Android技术知识Android开发Android开发
谷歌架构组件(三)LiveData的使用与分析

谷歌架构组件(三)LiveData的使用与分析

作者: wenson123 | 来源:发表于2018-03-01 14:41 被阅读2791次

LiveData is an observable data holder class.从谷歌的解释中我们可以知道LiveData是一个可观察的数据持有类。和普通的observable不同的是,LiveData可以感知activity,fragment,service等组件的生命周期变化,从而确保数据的更新是在组件的active状态周期执行。

使用LiveData具有如下优势:

确保UI和数据状态保持一致

LiveData属于观察者模式。当生命周期变化或者数据更新时,LiveData通知Observer对象发生变化,由observer的onChange响应执行UI更新。

没有内存泄漏

Observers 是和LifeCycle对象绑定的,当LifeCycle对象被onDestroy()时,observers则被clean up。

在stop activities时不会奔溃

当Observers的生命周期处于inactive状态时,例如activity被按返回键时,Observers将不会响应来自LiveData的事件。

不需要更多的手动管理生命周期

LiveData 负责自动管理生命周期

保证数据是最新的

比如处于后台的activity重新回到前台时,它将自动获得最新的数据。

响应屏幕旋转等配置变化

当activity或者fragment因为屏幕旋转,或者语言等配置改变而重建时,它将接收最新的数据。

共享资源

你可以extend LiveData,利用单例模式封装一些系统服务,当LiveData对象和系统服务连接后,所有需要该系统服务提供资源的observer可改为直接观察这个LiveData.

如何使用LiveData

  1. 创建LiveData实例持有特定类型的数据,通常放在你的自定义ViewModel类中。
public class NameViewModel extends ViewModel {

// Create a LiveData with a String
private MutableLiveData<String> mCurrentName;

    public MutableLiveData<String> getCurrentName() {
        if (mCurrentName == null) {
            mCurrentName = new MutableLiveData<String>();
        }
        return mCurrentName;
    }

// Rest of the ViewModel...
}

  1. 创建Observer对象实现onChanged()函数,当LiveData对象持有的数据发生更改后,或activity,fragment等生命周期变化时,比如从后台进入前台时,onChanged()会被触发调用。

  2. 将Observer对象使用observer()函数attach到LiveData对象。

public class NameActivity extends AppCompatActivity {

    private NameViewModel mModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Other code to setup the activity...

        // Get the ViewModel.
        mModel = ViewModelProviders.of(this).get(NameViewModel.class);

        // Create the observer which updates the UI.
        final Observer<String> nameObserver = new Observer<String>() {
            @Override
            public void onChanged(@Nullable final String newName) {
                // Update the UI, in this case, a TextView.
                mNameTextView.setText(newName);
            }
        };

        // Observe the LiveData, passing in this activity as the LifecycleOwner and the observer.
        mModel.getCurrentName().observe(this, nameObserver);
    }
}
更新LiveData 对象

调用LiveData的setValue()后,会直接触发Observer对象的onChange()函数。 如果是在非UI线程,调用postValue()函数。

eg:

mButton.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        String anotherName = "John Doe";
        mModel.getCurrentName().setValue(anotherName);
    }
});

响应式编程

如果你希望支持RxJava,可添加支持

dependencies {
    // ReactiveStreams support for LiveData
    implementation "android.arch.lifecycle:reactivestreams:1.1.0"
}


关于LiveData的高级用法:扩展Extend,转化Transform,合并Merge,本文不多介绍,感兴趣的同学请参考谷歌官网链接

代码分析:
livedata.png

LiveData的整体类组织关系还是非常清晰的。

核心类 LiveData


public abstract class LiveData<T> {


    /**
    * 添加observe对象
    **/
    @MainThread
    public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<T> observer) {
       ......
    }
    
    /**
    * 更新持有数据,触发onserve对象onChange()执行
    **/
    @MainThread
    protected void setValue(T value) {
       ......
        mData = value;
        dispatchingValue(null);
    }
    
   
    /**
    * 非UI线程更新持有数据
    **/
    protected void postValue(T value) {
       ......
    }
    
    /**
    * 当observe对象个数从0到1时,被调用
    **/
    protected void onActive() {

    }
    
    
    /**
    * 当observe对象个数从1到0时,被调用
    **/
    protected void onInactive() {

    }    

}

MutableLiveData 类继承于LiveData, 公开暴露postValue,setValue两个方法。

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


MediatorLiveData 类继承于MutableLiveData, 可观察多个LiveData对象,响应来自所观察LiveData对象的onChanged事件。

public class MediatorLiveData<T> extends MutableLiveData<T> {
    private SafeIterableMap<LiveData<?>, Source<?>> mSources = new SafeIterableMap<>();


   /**
     * Starts to listen the given {@code source} LiveData, {@code onChanged} observer will be called
     * when {@code source} value was changed.
     **/
    @MainThread
    public <S> void addSource(LiveData<S> source, Observer<S> onChanged) {
       ......
    }

    /**
     * Stops to listen the given {@code LiveData}.
     *
    */
    @MainThread
    public <S> void removeSource(LiveData<S> toRemote) {
        ......
    }

    ......
}


参考:
  1. 谷歌官网LiveData
  2. Android 8.1 source code

相关文章

网友评论

    本文标题:谷歌架构组件(三)LiveData的使用与分析

    本文链接:https://www.haomeiwen.com/subject/eabgxftx.html