当前位置:网站首页>LiveData : Transformations.map和 Transformations.switchMap用法
LiveData : Transformations.map和 Transformations.switchMap用法
2022-08-09 22:11:00 【猿小帅01】
项目背景 : 某个int值,在A页面需要获取它的显示int数值,在B页面需要需要将int值转换为String字符串
1. Transformations.map
基于此背景,此文介绍下Transformations.map和Transformations.switchMap,数据源A监听数据源B的内容,变化时将B
的内容转化为相应的其他内容并且通知给A数据源的观察者。
案例
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的内容的变化, 变化时从B内容获取相应的数据源C, 添加到A的监听列表
即 A 同时监听B和C ,B内容的变化只会(switch)更换A监听列表里的C,C内容的变化才会通知A监听器
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
}
}
边栏推荐
猜你喜欢
EasyExcel使用
少儿编程 电子学会图形化编程等级考试Scratch三级真题解析(判断题)2022年6月
测试2年,当时身边一起入行的朋友已经月薪20k了,自己还没过万,到底差在了哪里?
金仓数据库 KingbaseGIS 使用手册(6.4. 几何对象存取函数)
OSG笔记:使用setFontResolution设置字体分辨率
Install win7 virtual machine in Vmware and related simple knowledge
伦敦银行情中短线的支撑和阻力位
YGG 经理人杯总决赛已圆满结束,来看看这份文字版总结!
数字与中文大写数字互转(5千万亿亿亿亿以上的数字也支持转换)
离散选择模型之Gumbel分布
随机推荐
CV复习:softmax代码实现
全球不用交税的国家,为什么不交
c:forEach varStatus属性
Users should clearly know that quantitative trading is not a simple procedure
上海一科技公司刷单被罚22万,揭露网络刷单灰色产业链
五分钟商学院(基础---商业篇)
高数_复习_第4章:向量代数和空间解析几何
用PLSQL导出Oracle一个表
请讲一讲JS中的 for...in 与 for...of (上)
Miscellaneous talk - the sorrow of programmers
高手这样看现货白银走势图
leetcode:332. 重新安排行程
tiup cluster start
LeetCode_2632_字符串压缩
Leetcode 530. 二叉搜索树的最小绝对差
tiup cluster template
JS--popstate事件--使用/教程/实例
JS--hashchange事件--使用/教程
学习编程的第十二天
联盟链技术应用的难点