HarmonyOS鸿蒙Next中map和switchMap

HarmonyOS鸿蒙Next中map和switchMap

map和switchMap

map方法用于将实际包含数据的LiveData和仅用于观察数据的LiveData进行转换:比如User类里包含name和age,如果现在要求只要显示name,不关心age,我们就可以用map进行转换

class MainViewModel(countReserved:Int) : ViewModel() {
    private val userLiveData = MutableLiveData<User>()
    val userName: LiveData<String> =
        userLiveData.map { user -> "${user.firstName} ${user.lastName}" }
//书中的Transformation已经被弃用,直接用LiveData 的map,直接传入转换函数
}

switchMap

当ViewModel中的LiveData是调用另外的方法获取的,那我们就可以借助switchMap方法

viewModel.getUser(userId = "10")
    .observe(this, Observer { count1 -> binding.infoText.text = count1.toString() })
//  如果这样写那么每次调用getUser都会创建新的实例,但是observe和老的实例绑定所以会一直观察老的LiveData实例
  1. 定义一个新的userIdLiveData观察userId
class MainViewModel(countReserved: Int) : ViewModel() {

private val userIdLiveData=MutableLiveData<String>()
    //调用userIdLiveData的switchMap将Repository中不可观察的LiveData转换为另一个可观察的LiveData
    val user:LiveData<User> =userIdLiveData.switchMap { userId1->Repository.getUser(userId1) }
    
}


fun getUser(userId:String){
   userIdLiveData.value=userId
}


object Repository {
    fun getUser(userId:String): LiveData<User> {
        val liveData= MutableLiveData<User>()
        liveData.value=User(userId,userId,0)
        return  liveData
    }
}
    
binding.getUserBtn.setOnClickListener {
    val  useId=(0.0..1000).random().toString()
    viewModel.getUser(useId)//当userIdLiveData的值发生变化,则观察他的switchMap就会执行,然后Repository.getUser()获取真正的用户数据,然后返回一个可观察的LiveData,在Activity中只需要观察这个就行了
}
viewModel.user.observe(this,Observer{
    user->binding.infoText.text=user.firstName
})

如果要获取ViewModel中某个数据的方法是没有参数的,那么我们可以创立一个空的LiveData,泛型指定为Any?

private val refreshLiveData=MutableLiveData<Any?>()
val refreshResult=refreshLiveData.switchMap{Repository.refresh()}//假设这个方法存在
fun refresh(){
refreshLiveData.value=refreshLiveData.value
}

更多关于HarmonyOS鸿蒙Next中map和switchMap的实战教程也可以访问 https://www.itying.com/category-93-b0.html

2 回复

在HarmonyOS鸿蒙Next中,mapswitchMap是响应式编程中常用的操作符。map用于将数据流中的每个元素转换为另一种形式,例如将原始数据映射为UI显示所需格式。switchMap用于在数据流转换时切换到新的数据流,常用于处理异步操作(如网络请求),确保只处理最新请求的结果。两者均基于ArkTS的响应式能力实现,适用于状态管理和事件处理场景。

更多关于HarmonyOS鸿蒙Next中map和switchMap的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS Next中,map和switchMap是LiveData转换的重要操作符。map用于数据格式转换,而switchMap用于处理动态数据源切换。

map操作符:

  1. 对原始LiveData的值进行转换
  2. 返回一个新的LiveData实例
  3. 适用于简单的数据格式转换场景
  4. 转换是同步执行的

switchMap操作符:

  1. 根据源LiveData的值动态切换数据源
  2. 自动取消前一个数据源的观察
  3. 适用于依赖动态参数获取数据的场景
  4. 转换是异步执行的

关键区别:

  • map是1:1转换,switchMap是1:N转换
  • switchMap会取消前一个LiveData的订阅
  • switchMap更适合网络请求等异步场景

在示例代码中,switchMap的使用方式是正确的,通过userIdLiveData触发数据获取,避免了直接观察getUser()返回的LiveData导致的内存泄漏问题。对于无参数方法,使用Any?类型的LiveData作为触发器也是常见做法。

回到顶部