当前位置:网站首页>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
}
}
边栏推荐
猜你喜欢
随机推荐
浅析量股票化交易的发展现状
正则表达式的实际使用
leetcode:319. 灯泡开关
如何知道电脑开机记录?
Redis集群
leetcode:323. 无向图中连通分量的数目
毕昇编译器优化:Lazy Code Motion
shader学习笔记(五)
Leetcode 236. 二叉树的最近公共祖先
c:forEach varStatus属性
为什么刀具数据库无法打开?
如何坚持使用程序化系统?
Qt 消息机制和事件
DXF笔记:文字对齐的研究
用户要清晰知道,量化交易并非简单的程序
The 2022-8-9 sixth group of input and output streams
测试2年,当时身边一起入行的朋友已经月薪20k了,自己还没过万,到底差在了哪里?
YGG 经理人杯总决赛已圆满结束,来看看这份文字版总结!
Basic operations of xlrd and xlsxwriter
JS--hashchange事件--使用/教程









