LiveData 不更新
LiveData does not update
class RequestViewModel(private val repository: RequestRepository) : ViewModel() {
// request currency type
private val currencySearchType = MutableLiveData<String>()
val requests: LiveData<PagedList<Request>> = repository.getRequests(currencySearchType.value!!)
fun updateSearchType(type: String) {
currencySearchType.postValue(type)
}}
以上是我的viewModel中的代码。
private fun initAdapter() {
recyclerView.adapter = adapter
viewModel.requests.observe(viewLifecycleOwner, Observer {
adapter.submitList(it)
})
}
这是片段中的代码。所以基本上,我所做的是在 viewModel 中观察 "requests",在片段中,我还将调用 updateSearchType 来更新 currencySearchType。我希望一旦 currencySearchType 改变,那么 viewmodel.requests 也会改变。但事实证明,这些请求再也不会被调用了。有谁知道哪里出了问题?感谢您的帮助!
更改 currencySearchType 的值不会触发您只是将其用作函数参数的实时数据。你必须为此使用转换。
https://developer.android.com/reference/android/arch/lifecycle/Transformations
class RequestViewModel(private val repository: RequestRepository) : ViewModel() {
// request currency type
lateinit var currencySearchType:String
val requests: LiveData<PagedList<Request>> = Transformations.switchMap(currencySearchType) { repository.getRequests(it) }
fun updateSearchType(type: String) {
currencySearchType = type
}}
class RequestViewModel(private val repository: RequestRepository) : ViewModel() {
// request currency type
private val currencySearchType = MutableLiveData<String>()
val requests: LiveData<PagedList<Request>> = repository.getRequests(currencySearchType.value!!)
fun updateSearchType(type: String) {
currencySearchType.postValue(type)
}}
以上是我的viewModel中的代码。
private fun initAdapter() {
recyclerView.adapter = adapter
viewModel.requests.observe(viewLifecycleOwner, Observer {
adapter.submitList(it)
})
}
这是片段中的代码。所以基本上,我所做的是在 viewModel 中观察 "requests",在片段中,我还将调用 updateSearchType 来更新 currencySearchType。我希望一旦 currencySearchType 改变,那么 viewmodel.requests 也会改变。但事实证明,这些请求再也不会被调用了。有谁知道哪里出了问题?感谢您的帮助!
更改 currencySearchType 的值不会触发您只是将其用作函数参数的实时数据。你必须为此使用转换。
https://developer.android.com/reference/android/arch/lifecycle/Transformations
class RequestViewModel(private val repository: RequestRepository) : ViewModel() {
// request currency type
lateinit var currencySearchType:String
val requests: LiveData<PagedList<Request>> = Transformations.switchMap(currencySearchType) { repository.getRequests(it) }
fun updateSearchType(type: String) {
currencySearchType = type
}}