当前位置:网站首页>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
}
}
边栏推荐
猜你喜欢
随机推荐
深圳堡垒机厂家有哪些?重点推荐哪家?
Transfer Learning & Kemin Initialization
Leetcode 530. 二叉搜索树的最小绝对差
What kind of mentality do you need to have when using the stock quantitative trading interface
Miscellaneous talk - the sorrow of programmers
JS中表单操作、addEventListener事件监听器
深入理解多线程(第一篇)
【面试高频题】可逐步优化的链表高频题
tiup cluster stop
matplotlib散点图颜色分组图例
五分钟商学院(基础---商业篇)
【JZOF】32从上往下打印二叉树
金仓数据库 KingbaseGIS 使用手册(6.3. 几何对象创建函数)
JS--hashchange事件--使用/教程
如何正则匹配乱码?
EasyExcel使用
String类常用方法
Analyses the development status quo of stock trading
iNFTnews | 迪士尼如何布局Web3
“我“是一名测试/开发程序员,小孙的内心独白......