当前位置:网站首页>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
}
}
边栏推荐
- ElasticSearcch集群
- What is the stability of the quantitative trading interface system?
- SRv6性能测量
- The 2022-8-9 sixth group of input and output streams
- 安踏携手华为运动健康共同验证冠军跑鞋 创新引领中国体育
- Sun Zhengyi lost 150 billion: it was expensive at the beginning
- k8s部署mysql
- What kind of mentality do you need to have when using the stock quantitative trading interface
- Install win7 virtual machine in Vmware and related simple knowledge
- CGLIB源码易懂解析
猜你喜欢
torch.distributed多卡/多GPU/分布式DPP(二)——torch.distributed.all_reduce(reduce_mean)&barrier&控制进程执行顺序&随机数种子
Transfer Learning & Kemin Initialization
毕昇编译器优化:Lazy Code Motion
shell数组
matplotlib散点图颜色分组图例
测试2年,当时身边一起入行的朋友已经月薪20k了,自己还没过万,到底差在了哪里?
五分钟商学院(基础---商业篇)
都在说云原生,那云原生到底是什么?
ArrayList 和 LinkedList 区别
带着昇腾去旅行:一日看尽金陵城里的AI胜景
随机推荐
OFDM 十六讲 7 - Inter-Symbol-Interference
Janus Official DEMO Introduction
金仓数据库 KingbaseGIS 使用手册(6.3. 几何对象创建函数)
daemon
制定量化交易策略的基本步骤有哪些?
Leetcode 701. 二叉搜索树中的插入操作
HBuilder X 不能运行到内置终端
web 面试高频考点 —— 性能优化篇(手写防抖、手写节流、XXS攻击、XSRF攻击)
伦敦银行情中短线的支撑和阻力位
学习编程的第十二天
五分钟商学院(基础---商业篇)
正则表达式的实际使用
Sun Zhengyi lost 150 billion: it was expensive at the beginning
xlrd 与 xlsxwritter 的基本操作
VR全景结合小程序,为线上电商更好的服务
Leetcode 235. 二叉搜索树的最近公共祖先
matplotlib散点图自定义坐标轴(文字坐标轴)
PyQt5:入门使用教程
生成NC文件时,报错“未定义机床”
毕昇编译器优化:Lazy Code Motion