【问题标题】:MutableLiveData switchMap never calledMutableLiveData switchMap 从未调用过
【发布时间】:2021-08-22 11:51:09
【问题描述】:

我正在尝试使用 MutableLiveDataswitchMap() 更新我的列表,即使我将新值发布到 LiveData switchMap() 从未调用过。

这是我如何更新 MutableLiveData 从我的:

 viewModel.getProductListingById(queryModelId)
viewModel 中的

getProductListingById() 实现:

fun getProductListingById(newQueryModelId: ProductListingQueryModelId) {
        queryModelId.postValue(newQueryModelId)
    }

这是我如何定义 queryModelId

    private val queryModelId = MutableLiveData<ProductListingQueryModelId>()

最后是switchMap()

val productListingId = queryModelId.switchMap { query ->
        //This log statement never called
        Log.e("ProductViewModel ","id =${query.id}")
        productListingRepo.getProductListingById(query.id.toInt(), query.body).cachedIn(viewModelScope)
    }

【问题讨论】:

  • newQueryModelId 是一个全新的对象吗?还是已经保存在MutableLiveData 中的同一对象,但具有不同的属性?换句话说,尝试构建一个全新的ProductListingQueryModelId,使用所有正确的属性对其进行初始化,然后将其传递给getProductListingById()
  • 是的,它是一个新对象

标签: android kotlin android-livedata android-jetpack android-viewmodel


【解决方案1】:

最后我找到了你必须确保你观察你的 LiveData 的问题 在你的 ui 中,所以在我的情况下,val productListingId 在我的 ui 中添加观察者后从未在我的 ui 中观察到每件事都按预期工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-07
    • 2020-11-27
    • 1970-01-01
    • 1970-01-01
    • 2019-05-02
    • 2014-11-23
    • 2017-08-27
    • 2012-08-09
    相关资源
    最近更新 更多