Android Kotlin中的泛型和可变LiveData

Android Kotlin中的泛型和可变LiveData,android,generics,kotlin,android-livedata,Android,Generics,Kotlin,Android Livedata,我有两个非常相似的函数,我试图通过使用泛型来避免代码中的重复。这些函数都有一个try-catch块,并使用两种不同类型的MutableLiveData通知其观察者: val nowastericipesposts:MutableLiveData=MutableLiveData() val lastArticlesPosts:MutableLiveData=MutableLiveData() 趣味GetNowastericiposts(){ makeCall(service.getRecipes(

我有两个非常相似的函数,我试图通过使用泛型来避免代码中的重复。这些函数都有一个try-catch块,并使用两种不同类型的MutableLiveData通知其观察者:

val nowastericipesposts:MutableLiveData=MutableLiveData()
val lastArticlesPosts:MutableLiveData=MutableLiveData()
趣味GetNowastericiposts(){
makeCall(service.getRecipes(),noWasteRecipesPosts)
范围.发射{
试一试{
val response=service.getRecipes().await()
何时(response.isSuccessful){
正确->{
response.body()?.let{
nowastericipesposts.postValue(ArrayList(response.body()))
}?:运行{
errorLiveData.postValue(response.message())
}
}
false->errorLiveData.postValue(response.message())
}
}捕获(e:例外){
noConnectionLiveData.postValue(true)
}
}
}
趣味getLastArticlesPosts(不包括配方:布尔值){
范围.发射{
试一试{
val响应=何时(不包括配方){
true->service.getLastArticles(categoriesToExclude=arrayListOf(BlogCategories.NO\u WASTE\u RECIPES.id))
.等待
false->service.getLastArticles()
.等待
}
何时(response.isSuccessful){
正确->{
response.body()?.let{
LastArticlesPost.postValue(ArrayList(response.body()))
}?:运行{
errorLiveData.postValue(response.message())
}
}
false->errorLiveData.postValue(response.message())
}
}捕获(e:例外){
noConnectionLiveData.postValue(true)
}
}
}
为了避免代码重复,我尝试使用泛型,但可能用错了。我已经定义了一个函数,该函数将延迟api响应作为第一个参数,我希望传递一个MutableLiveData以通知观察者作为第二个参数:

funmakecall(函数:Deferred,successLiveData:MutableLiveData){
范围.发射{
试一试{
val response=function.await()
何时(response.isSuccessful){
正确->{
response.body()?.let{
successLiveData.postValue(it)//此处编译错误
}?:运行{
errorLiveData.postValue(response.message())
}
}
false->errorLiveData.postValue(response.message())
}
}捕获(e:例外){
noConnectionLiveData.postValue(true)
}
}
}
不幸的是,我遗漏了一些内容,IDE在尝试发布LiveData值时给了我一个类型不匹配错误:

类型不匹配:必需:无!发现:任何

我很困惑,你对kotlin中的MutableLiveData和泛型有什么建议吗?

响应.body()类型和
MutableLiveData
类型必须匹配。函数签名应该是这样的:

fun <T> makeCall(function: Deferred<Response<T>>, successLiveData: MutableLiveData<T>)
funmakecall(函数:Deferred,successLiveData:MutableLiveData)

感谢您的回复,所以用任何一个替换星体投影就足够了?我想我已经试过了,但是没有success@NicolaGallazzi为什么有任何?将
T
放在示例中,它应该可以工作。注意,
fun
部分将
T
定义为类参数。明白了,现在明白了!我明天会试穿的,谢谢!