[Android-使用MutableLiveData的视图模型类型不匹配

问题描述 投票:0回答:1

我在我的应用程序中使用mvvm体系结构,这是我的代码:

    class ProductRepository : BaseRepository() {

    private var mutableLiveData = MutableLiveData<ProductsModel>()

fun getProducts(catId: String): MutableLiveData<ProductsModel> {
        if (internetAvailable) {
            scope.launch {
                val request = api.getProducts(catId)
                withContext(Dispatchers.Main) {
                    try {
                        val response = request.await()
                        mutableLiveData.value = response


                    } catch (e: HttpException) {
                        // Log exception //
                        Log.v("this", e.message);

                    } catch (e: Throwable) {
                        // Log error //)
                        Log.v("this", e.message);
                    }
                }
            }
        }
        return mutableLiveData
    }
}

存储库通过ProductsModel的值返回MutableLiveData。这是我的viewModel类:

class ProductsViewModel :ViewModel(){
    val repository=ProductRepository()

    private val _products=MutableLiveData<ProductsModel>()
    val products:LiveData<ProductsModel>
        get()=_products

    fun getProducts(catId:String){
        _products.value=repository.getProducts(catId)
    }
}

这是错误:enter image description here

我不明白此错误,该如何解决?为什么告诉我类型不正确?

android android-livedata android-viewmodel android-mvvm
1个回答
0
投票
您必须采用LiveData示例的值:

products.value=repository.getProducts(catId).value

但是最可取的方式是使用Transformations

private val catId = MutableLiveData<String>() val products: LiveData<ProductsModel> = Transformations.switchMap(catId) { catId-> if (query1 == null) { AbsentLiveData.create<ProductsModel>() } else { repositoryproducts.value=repository.getProducts(catId) } }

© www.soinside.com 2019 - 2024. All rights reserved.