【问题标题】:Using Transformations to transform a HashMap into a List使用 Transformations 将 HashMap 转换为 List
【发布时间】:2020-03-21 15:14:12
【问题描述】:

所以,我有一个视图模型,它将存储一个包含不同产品的 HashMap,这个 hashmap 将被更新/删除/创建,然后我需要将此 hashmap 转换为一个列表,所以在我的 UI 中我只返回修改后的 List

现在,这是我的视图模型

class SharedViewModel: ViewModel() {
    private val cartHashMap = MutableLiveData<HashMap<String,Cart>>()
    private var sharedHashMap = HashMap<String,Cart>()

fun setProductSelectedHashMap(productId:String,productSelected:Cart){
        sharedHashMap[productId] = productSelected
        cartHashMap.value = sharedHashMap
    }

    fun removeSelectedProduct(productId:String){
        sharedHashMap.remove(productId)
        cartHashMap.value = sharedHashMap
    }

    fun updateSelectedHashMap(productId:String,quantity:Int){
        val productCartSelected = sharedHashMap[productId]
        productCartSelected?.quantity = quantity
        sharedHashMap[productId] = productCartSelected!!
        cartHashMap.value = sharedHashMap
    }

}

所以,这里有一个我从另一个来源更新的 hashmap,这个 hashmap 将包含一个产品列表,这些产品将被删除、更新或添加到这个地图中。

每次发生这种情况时,我都想用 livedata 返回我的视图,该列表将包含我的 HashMap 所包含的内容,但我发现这是一种混淆如何使用 Transformations 将这些数据转换为列表的方式

我试过了

val getCart: LiveData<HashMap<String,Cart>> = Transformations.switchMap(cartHashMap, ::someFunc)
    private fun someFunc(myCartHash: HashMap<String,Cart>) = mutableListOf(myCartHash.values)

但是::someFunc 给了我一个错误,我使用 switchMap 因为数据会不断变化并且不会被映射一次,我只想将更新后的 hashmap 作为列表返回,其值与我的 hashmap 包含的值相同。

我该怎么做?

谢谢

【问题讨论】:

  • 我建议使用Transformations.map 而不是switchMap,因为之前的方法提供type T-&gt; R 转换,这是你的情况,而不是T-&gt; LiveData&lt;R&gt;

标签: android kotlin mvvm transformation android-architecture-components


【解决方案1】:

这样解决了

 val getCart: LiveData<MutableList<Cart>> = Transformations.switchMap(cartHashMap) {
        liveData(context = viewModelScope.coroutineContext + Dispatchers.IO) {
           emit(it.values.toMutableList())
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-28
    • 1970-01-01
    • 1970-01-01
    • 2011-07-24
    • 1970-01-01
    • 2011-07-25
    • 2018-07-16
    • 2016-06-27
    相关资源
    最近更新 更多