簡介
LiveData 是Jetpack中的一個組件,是一個可被觀察的數(shù)據(jù)存儲器類, 具有感知組件生命周期的能力,LiveData 可以感知組件生命周期活躍狀態(tài)發(fā)送數(shù)據(jù)更新,在組件銷毀時移除觀察者對象,大多結(jié)合具有生命周期的組件一起使用(如 Activity、Fragment 或 Service,或?qū)崿F(xiàn)了 LifecycleOwner 接口的對象)。
作用
那么 LiveData 有什么用呢?主要有如下兩個作用:
- 實時刷新數(shù)據(jù)
- 防止內(nèi)存泄漏
LiveData 采用的是觀察者模式,當(dāng) LiveData 保存的數(shù)據(jù)發(fā)生變化時就會通知觀察者,觀察者接收到通知后可以進(jìn)行 UI 數(shù)據(jù)刷新或者其他操作。
那它是怎么做到防止內(nèi)存泄漏的呢 ?在給 LiveData 添加觀察者對象的時候可以綁定一個具有生命周期的組件,當(dāng)組件生命周期處于活躍狀態(tài)(即 STARTED 、RESUMED 狀態(tài))時數(shù)據(jù)更新才會通知觀察者,當(dāng)組件被銷毀時則會自動移除對應(yīng)的觀察者對象,從而防止一直持有對應(yīng)組件防止內(nèi)存泄漏。
Hello LiveData
學(xué)習(xí)任何一個新技術(shù)我們習(xí)慣先來一個 Hello World,那么先來看一下 Hello LiveData 吧。
添加依賴
在 module 的 gradle.gradle 里引入 LiveData 包,如下:
dependencies {
def lifecycle_version = "1.1.1"
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation "android.arch.lifecycle:livedata:$lifecycle_version"
}
如果使用 Androidx 的話需要引入 Androidx 下的對應(yīng) LiveData 包和 appcompat 包:
dependencies {
def lifecycle_version = "1.1.1"
implementation 'androidx.appcompat:appcompat:1.0.0-beta01'
implementation "androidx.lifecycle:lifecycle-livedata:$lifecycle_version"
}
使用
依賴包引入進(jìn)來了,接下來看看怎么快速使用 LiveData
創(chuàng)建一個 MutableLiveData
對象,它是 LiveData 的子類,然后給它添加觀察者對象,代碼如下:
java:
final MutableLiveData<String> simpleLiveData = new MutableLiveData<>();
Observer<String> observer = new Observer<String>() {
@Override
public void onChanged(@Nullable String text) {
mTextView.setText(text);
}
};
simpleLiveData.observe(this, observer);
kotlin:
val simpleLiveData = MutableLiveData<String>()
val observer = Observer<String> { text ->
mTextView.text = text
}
simpleLiveData.observe(this, observer)
observe 方法中的
this
是實現(xiàn)了LifecycleOwner
接口的對象,比如 support 里的AppCompatActivity
等
當(dāng)我們對 simpleLiveData 數(shù)據(jù)進(jìn)行更新時且觀察者綁定的生命周期組件(如 Activity / Fragment 等實現(xiàn)了LifecycleOwner
接口的對象)處于活躍狀態(tài)即 STARTED
或 RESUMED
狀態(tài)時就會觸發(fā) Observer
的回調(diào)從而更新 mTextView 的值,即進(jìn)行 UI 數(shù)據(jù)更新。
比如點擊按鈕改變 simpleLiveData 的值為 "Hello LiveData" ,就會觸發(fā) Observer 的 onChanged 方法
mButton.setOnClickListener(view -> {
simpleLiveData.setValue("Hello LiveData")
});
概括如下 :
- 創(chuàng)建 LiveData 對象 :
new MutableLiveData<>()
- 創(chuàng)建觀察者對象:
new Observer()
- 綁定觀察者對象:
LiveData.observe
- 更新 LiveData 數(shù)據(jù):
LiveData.setValue
詳細(xì)介紹
1、Api 介紹
LiveData 是一個帶泛型的抽象類,有兩個子類 MutableLiveData
和 MediatorLiveData
下面看一下 LiveData 類的關(guān)系圖 :
-
public T getValue()
: 獲取 LiveData 里的數(shù)據(jù) -
public boolean hasActiveObservers()
: 是否存在活躍的觀察者對象 -
public boolean hasObservers()
:是否有觀察者對象 -
public void observe(LifecycleOwner owner, Observer<? super T> observer)
:添加感知生命周期的觀察者對象 -
public void observeForever(Observer<? super T> observer)
:添加無生命周期感知的觀察者對象 -
public void removeObserver(final Observer<? super T> observer)
:移除對應(yīng)的觀察者對象 -
public void removeObservers(final LifecycleOwner owner)
:根據(jù)生命周期對象移除觀察者對象 -
protected void setValue(T value)
:設(shè)置 LiveData 容器的數(shù)據(jù) -
protected void postValue(T value)
: 在主線程設(shè)置 LiveData 容器的數(shù)據(jù) -
protected void onActive()
:當(dāng)活躍的觀察者對象數(shù)量大于 0 時調(diào)用,即有活躍的觀察者對象時調(diào)用 -
protected void onInactive()
:當(dāng)活躍的觀察者對象數(shù)量等于 0 時調(diào)用,即無活躍的觀察者對象時調(diào)用
MutableLiveData
:可變的 LiveData,是我們最常用的 LiveData 子類。它的實現(xiàn)很簡單,就是繼承了 LiveData 然后向外暴露了 setValue
、postValue
方法
MediatorLiveData
:它繼承自 MutableLiveData 可以監(jiān)聽多個 LiveData 數(shù)據(jù)源,或者調(diào)度多個 LiveData 數(shù)據(jù)源決定向觀察者發(fā)送那個 LiveData 的數(shù)據(jù)更新。它新增了兩個方法 addSource
、removeSource
用于添加和刪除 LiveData 源
Observer
: 觀察者接口,通過該接口對 LiveData 數(shù)據(jù)進(jìn)行觀察
2、詳細(xì)使用
MutableLiveData 的使用
前面 Hello LiveData 簡單展示了 LiveData 的使用
LiveData 除了依賴生命周期對象實現(xiàn)觀察者的自動管理外,還可以添加忽略生命周期的觀察者, 使用 observeForever
方法:
java:
MutableLiveData<String> liveData = new MutableLiveData<>();
liveData.observeForever(new Observer<String>() {
@Override
public void onChanged(String s) {
//do something
}
});
kotlin:
val liveData = MutableLiveData<String>()
liveData.observeForever {
//do something
}
這種情況當(dāng)不需要進(jìn)行觀察的時候就需要手動調(diào)用 removeObserver
將觀察者移除,防止內(nèi)存泄漏。
變換操作 Transformations
上面介紹了 LiveData 的基礎(chǔ)使用,我們還可以使用 Transformations
對 LiveData 進(jìn)行變換操作,它提供了兩個操作符 map
和 switchMap
他們的作用都是將一個 LiveData 轉(zhuǎn)換為另一個 LiveData 對象,當(dāng)一個 LiveData 里的值發(fā)生改變時另一個 LiveData的值也隨之發(fā)生改變。 看一下具體如何使用, 使用 map
將 LiveData<User>
轉(zhuǎn)換為 LiveData<String>
:
java:
final MutableLiveData<User> userLiveData = new MutableLiveData<>();
final LiveData<String> userDescribe = Transformations.map(userLiveData, new Function<User, String>() {
@Override
public String apply(User user) {
return "id:" + user.getId() + ", name:" + user.getName() + ", age:" + user.getAge();
}
});
kotlin:
val userLiveData = MutableLiveData<User>()
val userDescribe = Transformations.map(userLiveData) { user ->
"id: ${user.id} name: ${user.name} age: ${user.age}"
}
當(dāng) userLiveData 的值發(fā)生改變時,userDescribe 的值也會隨之變化。
使用 switchMap
將 LiveData<Long>
轉(zhuǎn)換為 LiveData<User>
:
java:
private LiveData<User> getUser(long id){
//...
}
//....
final MutableLiveData<Long> userIdLiveData = new MutableLiveData<>();
final LiveData<User> userLiveData = Transformations.switchMap(userIdLiveData, new Function<Long, LiveData<User>>() {
@Override
public LiveData<User> apply(Long id) {
return getUser(id);
}
});
kotlin:
private fun getUser(id: Long): LiveData<User> {
//...
}
//...
val userIdLiveData = MutableLiveData<Long>()
val userLiveData = Transformations.switchMap(userIdLiveData) { id ->
getUser(id)
}
MediatorLiveData
MediatorLiveData
繼承自 MutableLiveData 可以添加多個 LiveData 數(shù)據(jù)源,可以觀察或調(diào)度多個 LiveData 數(shù)據(jù)源。前面介紹 Transformations 的變換操作實際上就是返回的 MediatorLiveData ,看一下 MediatorLiveData
的使用:
java:
MutableLiveData<User> userLiveData1 = new MutableLiveData<>();
MutableLiveData<User> userLiveData2 = new MutableLiveData<>();
MediatorLiveData<User> userMediatorLiveData = new MediatorLiveData<>();
userMediatorLiveData.addSource(userLiveData1, new Observer<User>() {
@Override
public void onChanged(User user) {
userMediatorLiveData.setValue(user);
}
});
userMediatorLiveData.addSource(userLiveData2, new Observer<User>() {
@Override
public void onChanged(User user) {
userMediatorLiveData.setValue(user);
}
});
kotlin:
val userLiveData1 = MutableLiveData<User>()
val userLiveData2 = MutableLiveData<User>()
val userMediatorLiveData = MediatorLiveData<User>()
userMediatorLiveData.addSource(userLiveData1) { user ->
userMediatorLiveData.value = user
}
userMediatorLiveData.addSource(userLiveData2) { user ->
userMediatorLiveData.value = user
}
上面我們?yōu)?userMediatorLiveData
添加了兩個 LiveData 源 userLiveData1
和 userLiveData2
,當(dāng)其中任意一個數(shù)據(jù)更新且在 userMediatorLiveData 的活躍生命周期內(nèi)就會更新 userMediatorLiveData。 有的人可能會有疑問用 MediatorLiveData
有什么用 ?感覺直接用 LiveData 好像也能實現(xiàn)相同的效果,給 userLiveData1 和 userLiveData1 設(shè)置監(jiān)聽然后將變化的數(shù)據(jù)設(shè)置給另一個 LiveData 好像也能達(dá)到效果,如下:
val userLiveData1 = MutableLiveData<User>()
val userLiveData2 = MutableLiveData<User>()
val userLiveData = MutableLiveData<User>()
userLiveData1.observe(this, Observer { user ->
userLiveData.value = user
})
userLiveData2.observe(this, Observer { user ->
userLiveData.value = user
})
這樣確實能實現(xiàn)上述相同的效果,區(qū)別在于 userLiveData1 和 userLiveData2 分別要設(shè)置 LifecycleOwner
而 MediatorLiveData
能統(tǒng)一管理添加到它內(nèi)部所有 LiveData 的生命周期, MediatorLiveData
重寫了 LiveData 的 onActive
和 onInactive
方法統(tǒng)一去添加和移除它內(nèi)部 LiveData 的 Observer
自定義LiveData
除了使用庫里提供的 MutableLiveData
和 MediatorLiveData
外我們還可以根據(jù)實際場景繼承 LiveData
自定義我們自己的 LiveData,比如我們需要展示最新一條消息的 MessageLiveData ,看看怎么實現(xiàn):
java:
public class MessageLiveData extends LiveData<String> {
private MessageManager messageManager;
public MessageLiveData(){
messageManager = MessageManager.getInstance();
}
//最新消息回調(diào)
private MessageManager.MessageCallback messageCallback = new MessageManager.MessageCallback() {
@Override
public void onMessage(String message) {
setValue(message);
}
};
@Override
protected void onActive() {
super.onActive();
messageManager.addMessageCallback(messageCallback);
}
@Override
protected void onInactive() {
super.onInactive();
messageManager.removeMessageCallback(messageCallback);
}
}
kotlin:
class MessageLiveData : LiveData<String>() {
private val messageManager:MessageManager by lazy{
MessageManager.getInstance()
}
private val messageCallback = MessageManager.MessageCallback { message ->
value = message
}
override fun onActive() {
super.onActive()
messageManager.addMessageCallback(messageCallback)
}
override fun onInactive() {
super.onInactive()
messageManager.removeMessageCallback(messageCallback)
}
}
MessageLiveData 繼承自 LiveData 在 onActive
里注冊消息監(jiān)聽,onInactive
里移除監(jiān)聽,這樣我們就可以使用 MessageLiveData 對最新消息進(jìn)行觀察。
LiveData 結(jié)合 ViewModel 使用
前面介紹 LiveData 的使用時都是直接在Activity里使用的,但是真實開發(fā)場景中我們一般不直接在 Activity / Fragment 中使用而是在 ViewModel 中使用,然后在 Activity / Fragment 中觀察 ViewModel 里 LiveData 數(shù)據(jù)的變化:
java:
public class MainViewModel extends ViewModel {
public MutableLiveData<User> userLiveData = new MutableLiveData<>();
public void loadUser(){
//...
userLiveData.setValue(user);
}
}
//Activity
MainViewModel viewModel = ViewModelProviders.of(this).get(MainViewModel.class);
viewModel.userLiveData.observe(this, new Observer<User>() {
@Override
public void onChanged(User user) {
mTextView.setText(user.getName());
}
});
kotlin:
class MainViewModel : ViewModel() {
var userLiveData = MutableLiveData<User>()
fun loadUser() {
//...
userLiveData.setValue(user)
}
}
//Activity
val viewModel = ViewModelProviders.of(this)[MainViewModel::class.java]
viewModel.userLiveData.observe(this, Observer { user ->
mTextView.text = user.name
})
關(guān)于
ViewModel
的詳細(xì)介紹請參考 Jetpack 之 ViewModel
LiveData 結(jié)合 DataBinding 使用
接下來看看 LiveData 結(jié)合 DataBinding 的使用,還是上面使用的 MainViewModel :
java:
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
binding.setLifecycleOwner(this);
MainViewModel viewModel = ViewModelProviders.of(this).get(MainViewModel.class);
binding.setVm(viewModel);
kotlin:
val binding = DataBindingUtil.setContentView<ActivityMainBinding>(this, R.layout.activity_main)
binding.setLifecycleOwner(this)
val viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)
binding.vm = viewModel
activity_main:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="vm"
type="com.example.livedata.MainViewModel"/>
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{vm.userLiveData.name}"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
這里 ViewModel 里我們沒有使用 DataBinding 的 Observable 而是使用的 LiveData ,在數(shù)據(jù)綁定的時候給 ViewDataBinding 設(shè)置了 LifecycleOwner
即 binding.setLifecycleOwner(this)
,當(dāng)數(shù)據(jù)綁定時 ViewDataBinding 內(nèi)部會自動給綁定的 LiveData 對象添加觀察者對象觀察數(shù)據(jù)的更新從而刷新 UI 數(shù)據(jù)。
關(guān)于
DataBinding
的詳細(xì)介紹請參考 Jetpack 之 DataBinding
原理
前面介紹了 LiveData 的使用,接下來看看 LiveData 內(nèi)部是怎么實現(xiàn)只在生命周期活躍狀態(tài)下回調(diào)觀察者的觀察方法的。
先看一下 observe
方法源碼:
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);
}
首先檢查是否在主線程,然后檢查生命周期狀態(tài),如果是 DESTROYED
即銷毀狀態(tài)則直接 return ,然后將 LifecycleOwner
和 Observer
封裝成 LifecycleBoundObserver
放入到 mObservers
Map 里并將其添加到生命周期觀察里。LifecycleBoundObserver
繼承自 ObserverWrapper
并實現(xiàn)了 GenericLifecycleObserver
接口,在 onStateChanged
里監(jiān)聽了生命周期的變化:
Override
public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
if (mOwner.getLifecycle().getCurrentState() == DESTROYED) {
removeObserver(mObserver);
return;
}
activeStateChanged(shouldBeActive());
}
在生命周期 DESTROYED
狀態(tài)將觀察者移除,其他狀態(tài)調(diào)用 activeStateChanged
方法去處理是否回調(diào)觀察者的回調(diào),這樣就達(dá)到了根據(jù)生命周期自動管理觀察者的目的。
然后再看 setValue
方法:
@MainThread
protected void setValue(T value) {
assertMainThread("setValue");
mVersion++;
mData = value;
dispatchingValue(null);
}
繼續(xù) dispatchingValue
方法:
void dispatchingValue(@Nullable ObserverWrapper initiator) {
if (mDispatchingValue) {
mDispatchInvalidated = true;
return;
}
mDispatchingValue = true;
do {
mDispatchInvalidated = false;
if (initiator != null) {
considerNotify(initiator);
initiator = null;
} else {
for (Iterator<Map.Entry<Observer<? super T>, ObserverWrapper>> iterator =
mObservers.iteratorWithAdditions(); iterator.hasNext(); ) {
considerNotify(iterator.next().getValue());
if (mDispatchInvalidated) {
break;
}
}
}
} while (mDispatchInvalidated);
mDispatchingValue = false;
}
重點在 considerNotify
方法:
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;
//noinspection unchecked
observer.mObserver.onChanged((T) mData);
}
先檢查 ObserverWrapper
即前面 observe
方法里封裝的 LifecycleBoundObserver
是否是活躍的,然后調(diào)用 shouldBeActive
方法,LifecycleBoundObserver
里其實就是判斷生命周期是否處于活躍狀態(tài)
@Override
boolean shouldBeActive() {
return mOwner.getLifecycle().getCurrentState().isAtLeast(STARTED);
}
然后是 ObserverWrapper
的最后版本與當(dāng)前版本的比較,如果>=
則 return,每次調(diào)用 setValue
方法當(dāng)前版本 mVersion++
,最后則是調(diào)用觀察者的回調(diào),即我們傳入的 Observer
的 onChanged
方法。
再來看 observeForever
方法:
@MainThread
public void observeForever(@NonNull Observer<? super T> observer) {
assertMainThread("observeForever");
AlwaysActiveObserver wrapper = new AlwaysActiveObserver(observer);
ObserverWrapper existing = mObservers.putIfAbsent(observer, wrapper);
if (existing != null && existing instanceof LiveData.LifecycleBoundObserver) {
throw new IllegalArgumentException("Cannot add the same observer"
+ " with different lifecycles");
}
if (existing != null) {
return;
}
wrapper.activeStateChanged(true);
}
它將 Observer
封裝成 AlwaysActiveObserver
,它的 shouldBeActive
方法直接返回 true
并調(diào)用 activeStateChanged(true);
設(shè)置 active 為 true,也就是一直處于活躍狀態(tài),所以能一直觀察數(shù)據(jù)的更新。
關(guān)于
Lifecycle
的詳細(xì)介紹請參考 Jetpack 之 Lifecycle
本文轉(zhuǎn)自 https://juejin.cn/post/7037409679420424199,如有侵權(quán),請聯(lián)系刪除。