当前位置:网站首页>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
}
}
边栏推荐
猜你喜欢
The 2022-8-9 sixth group of input and output streams
用PLSQL导出Oracle一个表
HUAWEI CLOUD escorts the whole process of "Wandering Ark" for the first time, creating a popular brand
技术盛宴!华云数据携六大议题亮相OpenInfra Days China
一体化伺服电机在三轴钻孔机中的应用
ElasticSearcch集群
2022-08-09 mysql/stonedb-子查询性能提升-概论
shader学习笔记(五)
Interfering with BGP routing---community attributes
金仓数据库 KingbaseGIS 使用手册(6.3. 几何对象创建函数)
随机推荐
Analyses the development status quo of stock trading
68.qt quick-qml多级折叠下拉导航菜单 支持动态添加/卸载 支持qml/widget加载等
带着昇腾去旅行:一日看尽金陵城里的AI胜景
力扣:518. 零钱兑换 II
【Leetcode】2104. Sum of Subarray Ranges
Miscellaneous talk - the sorrow of programmers
【JZOF】82二叉树中和为某一值的路径(一)
OFDM 十六讲 7 - Inter-Symbol-Interference
matplotlib散点图自定义坐标轴(文字坐标轴)
继承关系下构造方法的访问特点
Chapter 15 HMM模型
干涉BGP的选路---社团属性
毕昇编译器优化:Lazy Code Motion
Gartner全球集成系统市场数据追踪,超融合市场增速第一
华为云全流程护航《流浪方舟》破竹首发,打造口碑爆款
使用股票量化交易接口需要具备怎么样的心态
如何坚持使用程序化系统?
高手这样看现货白银走势图
学习编程的第十二天
1018.值周