简体   繁体   English

LiveData 转换 map 功能

[英]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.我知道我们可以使用mapswitchMap方法来转换 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 的一部分,它是ActivityFragment并且LiveDataViewModel的一部分,

  • Doing the transformations in 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的情况下,转换后的数据将被缓存,并且每次调用时都会提供。
  • Second thing is UI should be as dumb as possible, make all your data transformations before data reaches the UI.第二件事是 UI 应该尽可能的愚蠢,在数据到达 UI 之前进行所有的数据转换。 This way you can test your transformations using Unit Test without actually needing to rely on UI.这样您就可以使用单元测试来测试您的转换,而无需真正依赖 UI。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM