簡體   English   中英

我無法將值從掛起函數傳遞給 ViewModel

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM