Android LiveData Transformations

2020-11-22 22:58:52

参考地址 LiveData的数据转换 Transformations使用

有时候有这样的需求,需要在LiveData将变化的数据通知给观察者前,改变数据的类型;或者是返回一个不一样的LiveData。

这里介绍一个类Transformations,它可以帮助完成上面的这些操作。

Transformations.map()

//todo  LiveData创建方法1val liveData: MutableLiveData<NeiHanResult> = neiHanRepository.liveData
//todo LiveData创建方法2val liveData2 = Transformations.map(neiHanRepository.liveData) { it }!!Transformations.map()使用要修改后的数据对象val liveDataTemp = MutableLiveData<List<NeiHanResult2>>()//定义一个临时list存储对象var listData = mutableListOf<NeiHanResult2>()//todo  LiveData创建方法3 并修改数据val liveData3 = Transformations.map(neiHanRepository.liveData) {it.result.forEach { item ->val formattedTime = item.text + "66666"listData.add(NeiHanResult2(formattedTime, item.text))LogUtils.d(item.text)}//执行数据修改后 给新数据赋值liveDataTemp.value = listData}
//执行数据修改的方法neiHanViewModel.liveData3.observe(this, Observer {})//监听所需修改后数据neiHanViewModel.liveDataTemp.observe(this, Observer<List<NeiHanResult2>> {var text = ""it.forEach {text += "${it.name}:${it.text}\n"text_contact.text = text}})


  • 2018-02-23 14:22:50

    mysql的yearweek 和 weekofyear函数

    例如 2010-3-14 ,礼拜天 SELECT YEARWEEK('2010-3-14') 返回 11 SELECT YEARWEEK('2010-3-14',1) 返回 10 其中第二个参数是 mode ,具体指的意思如下: Mode First day of week Range Week 1 is the first week … 0 Sunday 0-53 with a Sunday in this year 1 Monday 0-53 with more than 3 days this year 2 Sunday 1-53 with a Sunday in this year 3 Monday 1-53 with more than 3 days this year 4 Sunday 0-53 with more than 3 days this year 5 Monday 0-53 with a Monday in this year 6 Sunday 1-53 with more than 3 days this year 7 Monday 1-53 with a Monday in this year 2.

  • 2018-02-23 17:20:44

    Mysql数据库If语句的使用

    MySQL的if既可以作为表达式用,也可在存储过程中作为流程控制语句使用,如下是做为表达式使用:

  • 2018-02-24 10:16:36

    Java工具类之Apache的Commons Lang和BeanUtils

    Apache Commons包估计是Java中使用最广发的工具包了,很多框架都依赖于这组工具包中的一部分,它提供了我们常用的一些编程需要,但是JDK没能提供的机能,最大化的减少重复代码的编写。