【发布时间】:2020-10-01 20:45:01
【问题描述】:
如果我从 Repository 类中的 getPopular 函数中删除返回类型,它可以工作,但我需要返回类型将其传递给视图模型。
存储库类
class HomeRepository {
suspend fun getPopular(): MutableLiveData<List<PopularResultsItem>>? {
val list:MutableLiveData<List<PopularResultsItem>>?=null
val client= RetrofitClient.getInstance().create(MoviesService::class.java).getPopular(API_KEY)
if(client.isSuccessful){
list?.postValue(client.body()?.results)
Log.d("HomeViewModel",client.body().toString())
}else{
Log.e("HomeViewModel",client.message())
}
return list
}
}
查看模型
class HomeViewModel : ViewModel() {
private val homeRepository= HomeRepository()
var listPopular = MutableLiveData<List<PopularResultsItem>>()
init {
getPopular()
}
private fun getPopular(){
viewModelScope.launch(IO) {
homeRepository.getPopular()
}
}
}
【问题讨论】:
-
这是你得到的整个堆栈跟踪,还是还有更多? (实际上复制和粘贴它也有帮助,这真的很难阅读。)我不确定是什么导致了
NullPointerException,但在您的代码中list始终为空。如果不是,但client.bodyis null,你最终会调用list.postValue(null)并且list不包含可空类型(它是<PopularResultsItem>而不是<PopularResultsItem?>
标签: android android-studio kotlin mvvm coroutine