Android 我能';t将值从挂起函数传递到ViewModel

Android 我能';t将值从挂起函数传递到ViewModel,android,android-studio,kotlin,mvvm,coroutine,Android,Android Studio,Kotlin,Mvvm,Coroutine,若我从存储库类中的getPopular函数中删除了返回类型,那个么它可以工作,但我需要返回类型将其传递给视图模型 存储库类 class HomeRepository { suspend fun getPopular(): MutableLiveData<List<PopularResultsItem>>? { val list:MutableLiveData<List<PopularResultsItem>

若我从存储库类中的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
        }
    }
类HomeRepository{
suspend fun getPopular():MutableLiveData{
val列表:MutableLiveData?=null
val client=reformationclient.getInstance().create(MoviesService::class.java).getPopular(API_键)
如果(客户端。成功){
list?.postValue(client.body()?.results)
Log.d(“HomeViewModel”,client.body().toString())
}否则{
Log.e(“HomeViewModel”,client.message())
}
返回列表
}
}
查看模型

class HomeViewModel : ViewModel() {
    private val homeRepository= HomeRepository()
    var listPopular = MutableLiveData<List<PopularResultsItem>>()

    init {
        getPopular()
    }

    private fun getPopular(){

        viewModelScope.launch(IO) {
           homeRepository.getPopular()
        }

    }

}
class HomeViewModel:ViewModel(){
private val homeRepository=homeRepository()
var listPopular=MutableLiveData()
初始化{
getPopular()
}
私人娱乐{
viewModelScope.launch(IO){
homeRepository.getPopular()
}
}
}
错误消息

看起来,您在后台启动了
挂起函数,因此
HomeViewModel.getPopular()
启动后完成,而不是在整个
HomeRepository.getPopular()执行后完成。如果任何人在该函数完成之前访问该对象,您可能会访问空值


launch
替换为
runBlocking
,问题就会出现。(如果没有代码的其余部分,就有点难以确定。)

您得到的是整个stacktrace,还是更多?(实际上,复制和粘贴它也很有帮助,这很难理解。)我不确定是什么导致了
NullPointerException
,但在你的代码
列表中,
总是空的。如果不是,但
client.body
为null,则最终调用
list.postValue(null)
并且
list
不包含可为null的类型(这是
而不是
我不建议使用
runBlocking
,因为顾名思义,您可能正在阻止该线程上的其他操作。我会将该列表初始化为空列表,这样您就不会得到NPE,并在该列表上添加一个观察者,这样您就可以在DB获取后获得正确的值。(LiveData也很酷)在此编辑之后,请与我一起工作
suspend fun getPopular():List?{val client=reformationclient.getInstance().create(MoviesService::class.java).getPopular(API_KEY)if(client.issusccessful){Log.d(“HomeViewModel”,client.body().toString())}else{Log.e(“HomeViewModel”,client.message())}返回client.body()?.results}