当前位置:网站首页>LiveData : Transformations.map and Transformations.switchMap usage
LiveData : Transformations.map and Transformations.switchMap usage
2022-08-10 00:32:00 【Ape Xiaoshuai 01】
项目背景 : 某个int值,在APage needs to be obtained it showsint数值,在BPage need toint值转换为String字符串
1. Transformations.map
基于此背景,This article introduceTransformations.map和Transformations.switchMap,数据源A监听数据源B的内容,Changes will beB
The content of the other contents into corresponding and notice toAData source of the observer.
案例
class CarViewModel : ViewModel() {
// 数据源 B
private var initialData = MutableLiveData<Int>()
/** * @describe 数据源A */
private var transformLiveData = Transformations.map(getInitialData()) {
when (it) {
0 -> "on"
else -> "off"
}
}
fun getInitialData(): MutableLiveData<Int> {
return initialData
}
}
2.Transformations.switchMap
数据源A监听数据源B的内容的变化, Change fromBContent to obtain the corresponding data sourceC, 添加到A的监听列表
即 A 同时监听B和C ,BThe change of the content will only(switch)更换AListen to the list ofC,CThe change of the content will informA监听器
class CarViewModel : ViewModel() {
// 数据源B
private val userLivedata = MutableLiveData<User>()
// 数据源C1
private val cFirstLiveData = MutableLiveData<Int>()
// 数据源C2
private val cSecondLiveData = MutableLiveData<Int>()
/** * 数据源A */
val mapLiveData = Transformations.switchMap(userLivedata) {
when (it.name) {
"test" -> cFirstLiveData
else -> cSecondLiveData
}
}
data class User(val name: String = "test", var age: Int = 18)
}
3.MediatorLiveData
合并两个LiveData
var count = 0
// A 数据
private val liveData1 = MutableLiveData<String>()
// B 数据
private val liveData2 = MutableLiveData<Int>()
val liveCombind = MediatorLiveData<String>()
init {
liveCombind.addSource(liveData1) {
addData()
}
liveCombind.addSource(liveData2) {
addData()
}
}
private fun addData() {
count++
if (count == 10) {
count = 0
//TODO
}
}
边栏推荐
猜你喜欢
随机推荐
matplotlib散点图颜色分组图例
金仓数据库 KingbaseGIS 使用手册(6.5. 几何对象编辑函数)
What is the stability of the quantitative trading interface system?
2020年度SaaS TOP100企业名单
【云原生】一文讲透Kubevela addon如何添加腾讯Crane
少儿编程 电子学会图形化编程等级考试Scratch三级真题解析(判断题)2022年6月
ElasticSearcch集群
CV复习:softmax代码实现
H5实现分享功能
mysql中的key是怎么用的,或者这个值有什么意义,如下图?
2022-8-9 第六组 输入输出流
【微信小程序开发(八)】音频背景音乐播放问题汇总
Sqlserver限制账户在哪些ip下才可以访问数据库
【JZOF】32从上往下打印二叉树
函数习题(下)
ArrayList 和 LinkedList 区别
迁移学习 & 凯明初始化
What are the basic steps to develop a quantitative trading strategy?
生成NC文件时,报错“未定义机床”
【燃】是时候展现真正的实力了!一文看懂2022华为开发者大赛技术亮点









