android-通过使用MutableLiveData

时间:2019-10-14 14:42:19

标签: android android-livedata android-viewmodel android-mvvm

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

class ProductRepository : BaseRepository() {

   private val 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

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

1 个答案:

答案 0 :(得分:0)

您必须采用LiveData示例的值:

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

但最可取的方法是使用Transformations

private val catId = MutableLiveData<String>()

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