我有两个非常相似的功能,我正尝试通过使用泛型来避免代码重复。这些函数都有一个try catch块,并使用两种不同类型的两个MutableLiveData通知其观察者:
val noWasteRecipesPosts: MutableLiveData<ArrayList<Recipe>> = MutableLiveData()
val lastArticlesPosts: MutableLiveData<ArrayList<Article>> = MutableLiveData()
fun getNoWasteRecipesPosts() {
makeCall(service.getRecipes(), noWasteRecipesPosts)
scope.launch {
try {
val response = service.getRecipes().await()
when (response.isSuccessful) {
true -> {
response.body()?.let {
noWasteRecipesPosts.postValue(ArrayList(response.body()))
} ?: run {
errorLiveData.postValue(response.message())
}
}
false -> errorLiveData.postValue(response.message())
}
} catch (e: Exception) {
noConnectionLiveData.postValue(true)
}
}
}
fun getLastArticlesPosts(excludeRecipes: Boolean) {
scope.launch {
try {
val response = when (excludeRecipes) {
true -> service.getLastArticles(categoriesToExclude = arrayListOf(BlogCategories.NO_WASTE_RECIPES.id))
.await()
false -> service.getLastArticles()
.await()
}
when (response.isSuccessful) {
true -> {
response.body()?.let {
lastArticlesPosts.postValue(ArrayList(response.body()))
} ?: run {
errorLiveData.postValue(response.message())
}
}
false -> errorLiveData.postValue(response.message())
}
} catch (e: Exception) {
noConnectionLiveData.postValue(true)
}
}
}
为了避免代码重复,我正在尝试使用泛型,但可能使用了错误的方式。我定义了一个将Deferred api响应作为第一个参数的函数,我想传递一个MutableLiveData作为第二个参数通知观察者:
fun makeCall(function: Deferred<Response<*>>, successLiveData: MutableLiveData<*>) {
scope.launch {
try {
val response = function.await()
when (response.isSuccessful) {
true -> {
response.body()?.let {
successLiveData.postValue(it) // Compile error here
} ?: run {
errorLiveData.postValue(response.message())
}
}
false -> errorLiveData.postValue(response.message())
}
} catch (e: Exception) {
noConnectionLiveData.postValue(true)
}
}
}
不幸的是,我丢失了一些东西,IDE尝试发布LiveData值时给了我Type Type不匹配的错误:
类型不匹配:必填:无!找到:任何。
我很困惑,关于kotlin中的MutableLiveData和泛型,您有什么建议吗?
response.body()
类型和MutableLiveData
类型必须匹配。函数签名应该是这样的:
fun <T> makeCall(function: Deferred<Response<T>>, successLiveData: MutableLiveData<T>)