【问题标题】:LiveData not updating on postValue()LiveData 未在 postValue() 上更新
【发布时间】:2019-11-28 12:56:47
【问题描述】:

我有以下用于搜索功能的 UI。

 View (UI)   <<  ViewModel()  << LiveData(Remote)
(Search UI)      (Search VM)     Fetch data from remote

如上所述,View 观察 ViewModel 中的特定方法,该方法返回 LiveData,如下所示:

override fun onStart() {
    super.onStart()
    viewModel.finalLiveData.observe(viewLifecycleOwner, listChangeObserver)
}

// Observer responsible for updating the UI via adapter.
private val listChangeObserver: Observer<List<User>> = Observer { users ->
      users?.let { updateUI(it) } ?: run { updateUI(emptyList()) }
}

override fun onStop() {
    viewModel.finalLiveData.removeObserver(listChangeObserver)
    super.onStop()
}

在 ViewModel 中,initSearch(searchKey:String) 过滤从远程接收到的 LiveData 并为 View 准备最后一个作为打击:

// Initiates the search with supplied search keys.
fun initSearch(searchInput: String?) {

    // filtering happens in Deserializer() class
    finalLiveData = Transformations.map(FirebaseQueryLiveData(query)) {
        repository.getSearchList(it, searchInput, searchLocation)
    }
}

并且initSearch 将从视图中调用为viewModel.initSearch(searchKey)。现在的问题是,finalLiveData 接收到来自转换的值,但不幸的是视图没有更新。

但是,请注意,如果用户尝试最近的应用并返回(通过调用 onPause()onResume()),数据会反映在视图中

有没有更好的方法来更新观察到的LiveData? 提前致谢。

【问题讨论】:

    标签: android android-lifecycle android-livedata android-architecture-components


    【解决方案1】:

    userListRemote 是您的仓库中的LiveData 吗?如果没有lifecycleowner,它将无法工作。

    您可以尝试直接映射到您的finalLiveData,而不是使用temp

    finalLiveData = Transformations.map(userListRemote, // do your mapping here)
    

    这样userListRemote会使用finalLiveDataviewLifecycleOwner

    【讨论】:

    • 谢谢杨。我尝试将 finalLiveData 与 finalLiveData = Transformations.map(userListRemote, Deserializer()) 的结果分配为 ​​MutableLiveData> 但视图未更新。我怀疑 View 观察者。
    • 虽然 LiveData 随结果更新,但视图并未随结果反映。外出时(最近的应用程序)并回来时更新视图。
    • 当然,View 和 ViewModel 交互在上述问题中是共享的。您还对哪些其他领域感兴趣?
    【解决方案2】:

    问题已解决。

    下面发布的解决方案。通过将 finalLiveData 设为可变数据并使用临时 LiveData、searchLiveData 来保存结果。当 searchLiveData 更新时,finalLiveData 也会更新。

    https://www.reddit.com/r/androiddev/comments/e9to2o/livedata_updates_are_not_reflecting_in_view/fant2x9?utm_source=share&utm_medium=web2x

    internal var finalLiveData = MutableLiveData<List<User>>()
    
    
    fun initSearch(searchInput: String?) {
        val searchLiveData = Transformations.map(FirebaseQueryLiveData(query)) {
            repository.getSearchList(it)
        }
    
        (searchLiveData as LiveData<List<User>>).observeForever { users ->
            finalLiveData.value = users
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多