来一起感受下LiveData和ViewModel的魅力吧!我的博客
一、导读
LiveData和ViewModel谷歌爸爸已推出很久!简单的说,LiveData和ViewModel都对Activity或Fragment的生命周期是有感知的,换句话说就是当activity或者fragment在活跃状态(STARTED或RESUMED)的时候,才干自己的活,当activity或fragment在销毁状态时,是不干活的!既然这样,那么就不会发生内存泄露!内存泄露不存在,光这一点你就很有必要在你的项目中使用。接下来,分别说一说LiveData和ViewModel。
二、LiveData
2.1 什么是LiveData?
/**
* LiveData is a data holder class that can be observed within a given lifecycle.
* This means that an {@link Observer} can be added in a pair with a {@link LifecycleOwner}, and
* this observer will be notified about modifications of the wrapped data only if the paired
* LifecycleOwner is in active state. LifecycleOwner is considered as active, if its state is
* {@link Lifecycle.State#STARTED} or {@link Lifecycle.State#RESUMED}. An observer added via
* {@link #observeForever(Observer)} is considered as always active and thus will be always notified
* about modifications. For those observers, you should manually call
* {@link #removeObserver(Observer)}.
*
* <p> An observer added with a Lifecycle will be automatically removed if the corresponding
* Lifecycle moves to {@link Lifecycle.State#DESTROYED} state. This is especially useful for
* activities and fragments where they can safely observe LiveData and not worry about leaks:
* they will be instantly unsubscribed when they are destroyed.
*
* <p>
* In addition, LiveData has {@link LiveData#onActive()} and {@link LiveData#onInactive()} methods
* to get notified when number of active {@link Observer}s change between 0 and 1.
* This allows LiveData to release any heavy resources when it does not have any Observers that
* are actively observing.
* <p>
* This class is designed to hold individual data fields of {@link ViewModel},
* but can also be used for sharing data between different modules in your application
* in a decoupled fashion.
*
* @param <T> The type of data held by this instance
* @see ViewModel
*/
LiveData是一个可被观察的数据持有者类,它只有在STARTED或者RESUMED状态时才会被激活,在DESTROYED状态时,会自动removeObserver(),在这也可以看出,它和普通的Observer不一样,它对生命周期是有感知能力的。有一种情况下,不会自动removeObserver():当你调用observeForever()方法的时候,你需要手动去调用removeObserver()方法。
2.2 LiveData的优点
<label style="color: red">下面是官方列出来的优点,我先用白话说下我在项目中使用LiveData,感受到的优点。</label>
1、没有内存泄露,可以放肆的去写你的代码;
2、横竖屏的时候,我不用去管如何保存数据状态,LiveData能保证我每次的数据都是最新的数据;
3、在MVVM中,View层只需要做数据的观察,展示UI就可以了,View和Model解耦,实现数据和视图分离;
1⃣️Ensures your UI matches your data state
LiveData follows the observer pattern. LiveData notifies Observer objects when the lifecycle state changes. You can consolidate your code to update the UI in these Observer objects. Instead of updating the UI every time the app data changes, your observer can update the UI every time there's a change.
2⃣️No memory leaks
Observers are bound to Lifecycle objects and clean up after themselves when their associated lifecycle is destroyed.
3⃣️No crashes due to stopped activities
If the observer's lifecycle is inactive, such as in the case of an activity in the back stack, then it doesn’t receive any LiveData events.
4⃣️No more manual lifecycle handling
UI components just observe relevant data and don’t stop or resume observation. LiveData automatically manages all of this since it’s aware of the relevant lifecycle status changes while observing.
5⃣️Always up to date data
If a lifecycle becomes inactive, it receives the latest data upon becoming active again. For example, an activity that was in the background receives the latest data right after it returns to the foreground.
6⃣️Proper configuration changes
If an activity or fragment is recreated due to a configuration change, like device rotation, it immediately receives the latest available data.
7⃣️Sharing resources
You can extend a LiveData object using the singleton pattern to wrap system services so that they can be shared in your app. The LiveData object connects to the system service once, and then any observer that needs the resource can just watch the LiveData object. For more information, see Extend LiveData.
2.3 LiveData的实战
看过源码之后,你会发现Google推荐我们将ViewModel和LiveData结合起来使用。话不多说,看代码吧!
class HomeViewModel : BaseViewModel() {
private var mHomeMsgData: MutableLiveData<T>? = null
val observeHomeMsgData: MutableLiveData<T>
get() {
if (mHomeMsgData == null) {
mHomeMsgData = MutableLiveData()
}
return mHomeMsgData!!
}
// 获取首页提示消息数量
fun postHomeMessageCount() {
// 请求相关数据
// 这里的T 指的是后台返回你数据的实体类。
val t = T()
mHomeMsgData!!.postValue(t)
}
}
class HomeActivity : BaseActivity<HomeViewModel>() {
onCreate(){
// ...
mViewModel.postHomeMessageCount()
}
mViewModel.observeHomeMsgData.observe(this, Observer {
when (it!!.code) {
// 做一些UI更新
// 你的代码你做主
}
})
}
以上代码就是LiveData和ViewModel的基本使用。
2.4 注意事项
MutableLiveData是LiveData的子类,只重写了两个方法,一个是postValue(T value),一个是setValue(T value)。postValue方法是在非UI线程调用,setValue方法在UI线程中调用。
三、ViewModel
3.1 ViewModel到底是什么?
把ViewModel拆分成“View-Model”,聪明的你应该能知道什么意思了吧!View和Model的桥梁,是不是和MVP中的Presenter挺像的。当然,需要我们注意的是ViewModel不能持有任何activity的上下文或者View的对象,否则就耦合了!!!
3.2 ViewModel的优化
上面代码中,ViewModel将来会承载很多数据相关的代码,既然ViewModel只做桥梁,那就不应该把Model层处理的东西全部放在ViewModel层中,所以我们要将数据相关的代码丢到别的地方去,我项目中是新增一个Repository层(其实就是Medel层),这一层做本地数据或者网络数据的相关操作
class FollowManagerViewModel : BaseViewModel() {
private var mLoadMoreData: MutableLiveData<T>? = null
val followRepository: FollowRepository<T>
get() {
return FollowRepository(mLoadMoreData!!)
}
val observeLoadMore: MutableLiveData<T>
get() {
if (mLoadMoreData == null) {
mLoadMoreData = MutableLiveData()
}
return mLoadMoreData!!
}
}
class FollowRepository<T : BaseResBean<T>>(private val mMutableLiveData: MutableLiveData<T>) {
fun loadMore() {
// 你的代码你做主
// 这里postValue把后台返回的数据对应的实体对象post出去
mMutableLiveData.postValue(t)
}
}
class HomeActivity : BaseActivity<FollowManagerViewModel>() {
onCreate(){
// ...
mViewModel!!.followRepository.loadMore()
}
mViewModel.observeLoadMore.observe(this, Observer {
when (it!!.code) {
// 做一些UI更新
// 你的代码你做主
}
})
}