LiveData是作为Lifecycle的一部分。我们看下官方文档是怎么介绍的。
LiveData是一个可被观察的伴有生命周期的数据持有类。这意味着观察者可以以配对的LifecycleOwner形式添加。如果配对LifecycleOwner数据发生改变,并且这个观察者的LifecycleOwner处于活动状态,那么观察者将会收到改变的通知。
LiveData在STARTED和RESUMED的时候处于活动状态,如果一个观察者是通过observeForever(Observer)添加的,那么她将永远处于活动状态,并且被修改的时候会收到通知。对于这些观察者,你需要手动调用removeObserver(Observer)。
如果相应的生命周期改变为DESTROYED状态,添加了生命周期的观察者将被自动删除。这对于Activity和Fragment特别有用,它们可以安全地观察 LiveData 而不必担心泄漏:当它们被销毁时,它们将立即取消订阅。
此外,LiveDataonActive()和onInactive()方法 .当活动观察者的数量在 0 和 1 之间变化时得到通知。这允许 LiveData当它没有任何观察者正在积极观察时释放任何大量资源。
此类旨在保存ViewModel的各个数据字段,但也可用于在应用程序中的不同模块之间以解耦方式共享数据。
0.LiveData是什么?
从官方文档的介绍可以做下面的总结。
- LiveData是用来保存数据的,并且和生命周期有关。
- 当处于STARTED和RESUMED状态的时候,LiveData总是活跃并且数据方式变化的时候,和她配对的观察者会得到通知。
- LiveData的主要目的是保存ViewModel的各个数据字段,但也可用于在应用程序中的不同模块之间以解耦方式共享数据。
- 不用担心内存泄漏问题,处于DESTROYED状态的时候自动删除观察者。
LiveData是在Lifecycle包下的一个类,自然是和生命周期有关的。并且LiveData是和ViewModel配合使用的。ViewModel不展开讲,将另写一篇。
1.实例讲解:评论点赞
我就不举类似User这种无聊的例子了。我们写一个真实的例子,就是评论点赞的例子。
需求是这样的,有点赞,踩,和分享三个按钮,以及两个文本分别表示点赞数和分享数量。布局效果如下。
布局实现:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".CommentActivity">
<TextView
android:id="@+id/tvLikeCount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.35"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.146" />
<TextView
android:id="@+id/tvShareCount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.642"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.146" />
<ImageView
android:id="@+id/imageThumbUp"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginTop="200dp"
android:contentDescription="TODO"
android:onClick="thumbUp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.171"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@drawable/ic_thumb_up" />
<ImageView
android:id="@+id/imageThumbDown"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginTop="200dp"
android:onClick="thumbDown"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@drawable/ic_thumb_down" />
<ImageView
android:id="@+id/imageShare"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginTop="200dp"
android:onClick="share"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.814"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@drawable/ic_share" />
</androidx.constraintlayout.widget.ConstraintLayout>
我们需要一个Comment类来描述点赞分享。就两个属性,这里使用了lombok来自动生成get set和构造器。手动写也可以。
@Data
@AllArgsConstructor
public class Comment {
private int shareCount;
private int likeCount;
}
下面就是我们最主要的代码了。下面的代码看起来挺多,其实都非常的简单。
第零步: 我们需要继承ViewModel,我们可以先不关系ViewModel是怎么回事,只关系LiveData的部分,然后再回头看ViewModel。
第一步: 声明一个MutableLiveData引用。这个MutableLiveData就是我们的LiveData本身,MutableLiveData只是个空壳类,没几行代码,继承自LiveData类。通过泛型包装了我们的数据bean Comment类,这样我们的Comment类就已经变成了"Live Data"。也就是这个Comment类已经”活"起来了,具有了可观察性。可以被Activity或者Fragment观察数据变化。
第二步: 为LiveData提供get方法给Activity或者Fragment调用,因为我们的数据最终是要在UI上面显示的。需要提供get方法给Activity或者Fragment调用获取数据。
第三步: 实现一些自定义的业务需求,这些需求都是和我们的Comment数据有关的。我们封装到ViewModel中,这样Activity和Fragment就不需要写这些代码了,直接调用就可以,实现了解耦和责任单一。Activity和Fragment只关系View层的事情,Model层的事情交给了ViewModel以及LiveData。
//第零步:继承ViewModel
public class CommentModel extends ViewModel {
//第一步:提供一个MutableLiveData包装数据。
private MutableLiveData<Comment> commentLiveData;
//第二步:为LiveData提供get方法给Activity或者fragment调用
public MutableLiveData<Comment> getCommentLiveData() {
if (commentLiveData == null) {
Comment comment = new Comment(0, 0);
commentLiveData = new MutableLiveData<>();
commentLiveData.setValue(comment);
}
return commentLiveData;
}
//第三步:实现自己的业务需求,这里我们实现了三个方法,分别对应点赞,踩和分享
/**
* 点赞+1
*/
public void likeCountPlus() {
Comment comment = commentLiveData.getValue();
if (comment != null) {
int likeCount = 0;
likeCount = comment.getLikeCount();
likeCount += 1;
comment.setLikeCount(likeCount);
commentLiveData.postValue(comment);
}
}
/**
* 点赞-1
*/
public void likeCountSub() {
Comment comment = commentLiveData.getValue();
if (comment != null) {
int likeCount = comment.getLikeCount();
likeCount -= 1;
comment.setLikeCount(likeCount);
commentLiveData.postValue(comment);
}
}
/**
* 分享+1
*/
public void shareCountplus() {
Comment comment = commentLiveData.getValue();
if (comment != null) {
int shareCount = comment.getShareCount();
shareCount += 1;
comment.setShareCount(shareCount);
commentLiveData.postValue(comment);
}
}
}
LiveData的基本用法就是上面这样,写在ViewModel内部。接下来,我们需要在Activity或者Fragment里面获取ViewModel和LiveData。
public class CommentActivity extends AppCompatActivity {
TextView tvLikeCount;
TextView tvShareCount;
private CommentModel commentModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_comment);
tvLikeCount = findViewById(R.id.tvLikeCount);
tvShareCount = findViewById(R.id.tvShareCount);
//可以封装
//第一步:创建ViewModel
commentModel = new ViewModelProvider(this).get(CommentModel.class);
//第二步:获取LiveData并添加观察者
commentModel.getCommentLiveData().observe(this, new Observer<Comment>() {
@Override
public void onChanged(Comment comment) {
//第三步:观察数据改变并做出响应
tvLikeCount.setText(String.valueOf(comment.getLikeCount()));
tvShareCount.setText(String.valueOf(comment.getShareCount()));
}
});
}
public void thumbUp(View view) {
commentModel.likeCountPlus();
}
public void thumbDown(View view) {
commentModel.likeCountSub();
}
public void share(View view) {
commentModel.shareCountplus();
}
}
第一步: 我们需要通过ViewModelProvider这个类获取到指定的ViewModel,这个是固定写法。
第二步: 通过ViewModel的get方法获取到LiveData,并且调用LiveData的observe方法开始观察数据变化,到这一步,整个逻辑已经完成。
第三步: 观察数据变化,并更新UI。数据变化是用户点击了相应的按钮,触发了ViewModel修改Comment类的数据,一旦数据发生变化,observe就会观察到,从而更新UI。
并且,因为ViewModel的特性,即使旋转屏幕,数据也不会丢失。