gpt4 book ai didi

android - LiveData 未在 postValue() 上更新

转载 作者:行者123 更新时间:2023-11-29 18:25:52 28 4
gpt4 key购买 nike

我有以下用于搜索功能的 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) 从 View 中调用。现在的问题是,finalLiveData 从转换中接收到值,但不幸的是 View 没有更新。

但是,注意到如果用户尝试最近的应用程序并返回(通过调用 onPause()onResume()),数据会反射(reflect)在 View 中

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

最佳答案

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

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

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

这样,userListRemote就会使用finalLiveDataviewLifecycleOwner

关于android - LiveData 未在 postValue() 上更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59089440/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com