[英]I can't pass value from suspend function to ViewModel
如果我從 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()
}
}
}
看起來,您在后台launch
了掛起功能,因此HomeViewModel.getPopular()
在launch
后完成,而不是在整個HomeRepository.getPopular()
執行后完成。 如果有人在該函數完成之前訪問該對象,則您可能會訪問空值。
用runBlocking
替換launch
,應該會出現問題。 (如果沒有其余的代碼,肯定很難知道。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.