Android Jetpack系列 之LiveData

Android Jetpack系列 之LiveData,第1张

概述前言在AndroidJetpack之ViewBinding和DataBinding这篇文章中,我们讲到了可观察的数据对象,在Jetpack组件中也为我们提供了强大的可观察的数据存储器类,就是我们本篇所说的LiveData。LiveData与普通可观察类不同的是LiveData具有生命周期感应能力,比如我们在页面中进行网络请求 前言

在Android Jetpack 之ViewBinding和DataBinding这篇文章中,我们讲到了可观察的数据对象,在Jetpack组件中也为我们提供了强大的可观察的数据存储器类,就是我们本篇所说的liveData。

liveData

与普通可观察类不同的是liveData具有生命周期感应能力,比如我们在页面中进行网络请求结束后,需要将数据显示在UI上,如果此时页面被销毁就会有空指针等异常,我们还需要在页面销毁的时候单独处理,而使用了liveData之后就不需要我们手动的去处理这些了。

liveData的使用

我们在lifecycle和viewmodel 的博文中以计数器为例子,这里我们仍然以计数器为例子,如果你还没看过之前的博文可移步:

Android Jetpack系列之Lifecycle 和 Android Jetpack系列之 ViewModel

首先来回顾下计数器的需求:


在Activity 可见的时候,我们去做一个计数功能,每隔一秒 将计数加1 ,当Activity不可见的时候停止计数,当Activity被销毁的时候 将计数置为0。这里我们新增需求将计数的数字显示在TextVIEw中。

所以我们就要做到当计数的数字发生改变时,通知TextVIEw便于TextVIEw重新显示,如果矬一点,可能会想到将VIEw传递到viewmodel中,让viewmodel持有VIEw的引用,这种方式确实可以实现需求,但是后患无穷,并且VIEw和viewmodel之前只能是单项的,即只能VIEw层持有viewmodel,那么如何优雅的实现找那个需求呢?这就是我们今天说的liveData了

我们在activity_main3中新增一个TextVIEw用来显示计数

<TextVIEw    androID:gravity="center"    androID:layout_margin="10dp"    androID:textSize="20dp"    androID:ID="@+ID/tv_count"    androID:layout_wIDth="match_parent"    androID:layout_height="wrap_content"/>

liveData需要结合viewmodel来使用,之前的Main3ActivityModel代码如下所示:

public class Main3Activityviewmodel extends viewmodel {    public int count = 0;    public Main3Activityviewmodel(int count) {        this.count = count;    }}

我们将count类型的变量修改为liveData的类型 代码如下所示:

public class Main3Activityviewmodel extends viewmodel {    public mutablelivedata<Integer> mCount = new mutablelivedata<>();    public Main3Activityviewmodel(int count) {        this.mCount.setValue(count);    }}

liveData类型的变量我们通过set和get去赋值和取值

现在计数的数字已经是liveData类型的了,那么我们如何在数据变化的时候通知textVIEw呢

我们只需要在Main3Activity中进行如下注册:

main3Activityviewmodel.count.observeForever(new Observer<Integer>() {    @OverrIDe    public voID onChanged(Integer integer) {          }});

光是这样还是不行的,我们还需要修改WorkUtil中的逻辑,因为现在是可变类型的数据,所以我们要将值的改变放在viewmodel中

public class Main3Activityviewmodel extends viewmodel {    public mutablelivedata<Integer> mCount = new mutablelivedata<>();    public voID add() {        mCount.setValue(mCount.getValue() + 1);    }    public Main3Activityviewmodel(int count) {        this.mCount.setValue(count);    }}

这样的话 我们在WorkUtil中调用add方法 就可以改变mCount的值了,最后我们在注册回到的onChanged方法中去给TextvIEw赋值就可以了,我们运行程序结果如下:

嚯嚯,pia pia 打脸

这里报错的原因是因为我们的计数demo是运行在子线程中的,而liveData的setValue方法只能在主线程中调用,如果想要在子线程中调动只能使用postValue方法,我们将赋值方法改为postValue,再次运行结果如下所示:

我不知道mac下是否有类似screenToGif这种软件,所以只能截静态图了。

ok,这样的话 我们就使用liveData实现上面的需求了,但是有没有感觉有什么问题呢,问题就是这个mCount可变类型的数据暴露给了外部,导致我们在viewmodel外也是可以赋值的,这样违反了viewmodel数据的封装性,所以我们需要将这个可变类型的变量声明为私有的并且声明一个不可变的变量赋值给mCount,只对外暴露不可变的liveData,修改model代码如下所示:

private liveData<Integer> count;public liveData<Integer> getCount() {    return mCount;}public voID setCount(liveData<Integer> count) {    this.count = count;}private mutablelivedata<Integer> mCount = new mutablelivedata<>();public voID add() {    mCount.postValue(mCount.getValue() + 1);}public Main3Activityviewmodel(int count) {    this.mCount.setValue(count);}

修改WorkUtil中的访问方法如下所示:

@OnlifecycleEvent(lifecycle.Event.ON_RESUME)public voID start() {    new Thread(new Runnable() {        @OverrIDe        public voID run() {            while (whetherToCount) {                try {                    Thread.sleep(1000);                    main3Activityviewmodel.add();                    Log.d(TAG, "start: " + main3Activityviewmodel.getCount());                } catch (InterruptedException e) {                    e.printstacktrace();                }            }        }    }).start();}

这样一来 就是liveData的规范用法了。

转换liveData

.map转换

为了说明转化的作用,我们新建一个Student类,类中有如下字段 :

public class Student {    /**     * 学号     */    private int stuNumber;    /**     * 姓名     */    private int stuname;    /**     * 分数     */    private int stuscore;    ....}

我们新建Main4Activity 对应页面输入分数、保存、显示分数

需求如下:

在输入框中输入分数、在textvIEw中显示分数

<EditText    androID:ID="@+ID/ed_socre"    androID:layout_wIDth="match_parent"    androID:layout_height="wrap_content"    androID:hint="enter stunumber" /><button    androID:ID="@+ID/btn_save"    androID:layout_wIDth="match_parent"    androID:layout_height="wrap_content"    androID:text="save" /><TextVIEw    androID:gravity="center"    androID:layout_margin="10dp"    androID:textSize="20sp"    androID:ID="@+ID/tv_stuscore"    androID:layout_wIDth="match_parent"    androID:layout_height="wrap_content" />

新建对应的Main4ActivityModel 来观察student数据的改变

public class Main4Activityviewmodel extends viewmodel {    private liveData<Student> liveData;    public liveData<Student> getliveData() {        return studentmutablelivedata;    }    private mutablelivedata<Student> studentmutablelivedata = new mutablelivedata<>();    public voID setStudentmutablelivedata(Student studentmutablelivedata) {      this.studentmutablelivedata.setValue(studentmutablelivedata);    }}

我们这里直接使用setStudentmutablelivedata来模拟数据的获取,正常情况下我们需要在viewmodel去请求网络数据进行设置

我们在Main4Activity中直接进行数据设置 *** 作:

private Main4Activityviewmodel main4Activityviewmodel;private button btnSave;private TextVIEw tvscore;private EditText edscore;private Student student = new Student();@OverrIDeprotected voID onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentVIEw(R.layout.activity_main4);    btnSave = findVIEwByID(R.ID.btn_save);    tvscore = findVIEwByID(R.ID.tv_stuscore);    edscore = findVIEwByID(R.ID.ed_socre);    main4Activityviewmodel = new viewmodelProvIDer(this).get(Main4Activityviewmodel.class);    student.setStuname("黄林晴");    student.setStuNumber(20200522);    btnSave.setonClickListener(new VIEw.OnClickListener() {        @OverrIDe        public voID onClick(VIEw v) {            student.setStuscore(Integer.parseInt(edscore.getText().toString()));            main4Activityviewmodel.setStudentmutablelivedata(student);        }    });    main4Activityviewmodel.getliveData().observe(this, new Observer<Student>() {        @OverrIDe        public voID onChanged(Student student) {            tvscore.setText("分数:" + student.getStuscore());        }    });}

这里只是个示例,不做空校验等问题了,我们运行程序,在输入框中输入100 结果如下所示:

程序达到了我们预期的结果,但是我们这里知道,对于学生这个属性来说,学号和姓名是不可变的,只有分数是可变的,所以这个时候我们可以使用map函数只对分数进行观察,改写viewmodel中的代码如下所示:

public Main4Activityviewmodel() {    stuscore = map(studentmutablelivedata, new Function<Student, Integer>() {        @OverrIDe        public Integer apply(Student input) {            final int stuscore = input.getStuscore();            return stuscore;        }    });}private liveData<Integer> stuscore;public liveData<Integer> getStuscore() {    return stuscore;}private mutablelivedata<Student> studentmutablelivedata = new mutablelivedata<>();public voID setStudentmutablelivedata(Student studentmutablelivedata) {    this.studentmutablelivedata.setValue(studentmutablelivedata);}

在Main4Activity监测score的变化

main4Activityviewmodel.getStuscore().observe(this, new Observer<Integer>() {    @OverrIDe    public voID onChanged(Integer integer) {        tvscore.setText("分数:" + integer);    }});

运行结果与上面一致,这就是map转换函数的用法

switchMap

我们上面的例子数据的获取是直接写在Activity中获取的,在真实的项目开发中,这里的数据一般都是从网络请求中或者缓存中获取的,我们来新建httpUtil来模拟数据的获取:

public class httpUtil {    public liveData<Student> getStudent(int score) {        mutablelivedata<Student> studentmutablelivedata = new mutablelivedata<>();        Student student = new Student();        student.setStuNumber(20200521);        student.setStuname("黄小仙");        student.setStuscore(score);        studentmutablelivedata.setValue(student);        return studentmutablelivedata;    }}

我们在viewmodel中也新增获取的方法:

public liveData<Student> getStudentMessage(int score) {    return new httpUtil().getStudent(score);}

然后就美滋滋的在Activity中进行如下注册:

main4Activityviewmodel.getStudentMessage(score).observe(this, new Observer<Student>() {    @OverrIDe    public voID onChanged(Student student) {        tvscore.setText("分数:" + student.getStuscore());    }});

OK,这种做法是不行的,原因很简单,因为我们的数据每次从网络中获取 获取到的都是一个新的liveData对象,所以我们无法监听到数据的变化,那么我们该如何做呢,这个时候switchMap就派上用场了

我们在viewmodel 中定义 检测分数变化的liveData对象

private mutablelivedata<Integer> score = new mutablelivedata<>();public voID setscore(int score) {    this.score.setValue(score);}

使用switchMap将信息转化为可观察的liveData对象:

private liveData<Student> studentliveData = transformations.switchMap(score, new Function<Integer, liveData<Student>>() {    @OverrIDe    public liveData<Student> apply(Integer input) {        return getStudentMessage(input);    }});

然后我们检测studentliveData的变化 ,在监听事件中设置分数

btnSave.setonClickListener(new VIEw.OnClickListener() {    @OverrIDe    public voID onClick(VIEw v) {        main4Activityviewmodel.setscore(Integer.parseInt(edscore.getText().toString()));    }});main4Activityviewmodel.studentliveData.observe(this, new Observer<Student>() {    @OverrIDe    public voID onChanged(Student student) {        tvscore.setText("分数:" + student.getStuscore());    }});

运行程序结果如下所示:

在实际项目开发中我们使用switchMap的频率还是很高的,毕竟 只要liveData对象是调用其他方法获取的 ,我们就可以这样做,

在点击事件中我们设置了可观察数据:分数,当分数改变的时候,就会执行switchMap函数 ,switchMap会将获取的数据转换为可观察的liveData,所以我们监听这个liveData对象 就可以观察到数据的变化了。

 

 

总结

以上是内存溢出为你收集整理的Android Jetpack系列 之LiveData全部内容,希望文章能够帮你解决Android Jetpack系列 之LiveData所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1060895.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-25
下一篇2022-05-25

发表评论

登录后才能评论

评论列表(0条)

    保存