[英]LiveData transformations map functionality
Recently i've been learning transformations methods on LiveData最近我一直在学习 LiveData 上的转换方法
I know that we can use map
or switchMap
method to transform livedata.我知道我们可以使用map
或switchMap
方法来转换 livedata。 Let's say we have Player data class similar below假设我们有类似下面的播放器数据 class
data class Player(val name: String, val score: Int = 0)
And we use map method to transform player livedata to playerName livedata我们使用 map 方法将 player livedata 转换为 playerName livedata
val player: LiveData<Player> = ...
val playerName: LiveData<String> =
Transformations.map(player) { it.name }
My question is, what is the difference doing it in observer function as they both run in main thread?我的问题是,在观察者 function 中这样做有什么区别,因为它们都在主线程中运行? I mean, if we want to get playerName then we can get it in observer function too.我的意思是,如果我们想获得 playerName,那么我们也可以在观察者 function 中获得它。 Why we declare second LiveData instance to get that为什么我们声明第二个 LiveData 实例来获得它
I took example code from this guide:https://proandroiddev.com/livedata-transformations-4f120ac046fc我从本指南中获取了示例代码:https://proandroiddev.com/livedata-transformations-4f120ac046fc
Assuming Observer
is part of Android UI which is Activity
or Fragment
and LiveData
is part of ViewModel
,假设Observer
是 Android UI 的一部分,它是Activity
或Fragment
并且LiveData
是ViewModel
的一部分,
Observer
will be local to that Observer
, if Activity gets restarted due to any Config
changes, your data inside Activity
will be destroyed unless you save it somehow, but LiveData
persists activity recreation, so if you have transformation in Observer side, it have to do it every time, but in case of LiveData
, transformed data will be cached and will be provided every time you call it.在Observer
中进行转换将是该Observer
本地的,如果 Activity 由于任何Config
更改而重新启动,除非您以某种方式保存它,否则您在Activity
中的数据将被销毁,但LiveData
持续重新创建活动,因此如果您在 Observer 端进行转换,它必须每次都这样做,但在LiveData
的情况下,转换后的数据将被缓存,并且每次调用时都会提供。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.