【问题标题】:I can't pass value from suspend function to ViewModel我无法将挂起函数的值传递给 ViewModel
【发布时间】: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.body is null,你最终会调用 list.postValue(null) 并且 list 不包含可空类型(它是 &lt;PopularResultsItem&gt; 而不是 &lt;PopularResultsItem?&gt;

标签: android android-studio kotlin mvvm coroutine


【解决方案1】:

看来,您 launch 在后台暂停功能,所以 HomeViewModel.getPopular()launch 之后完成,而不是在整个 HomeRepository.getPopular() 执行之后完成。如果有人在该函数完成之前访问该对象,您可能会访问空值。

launch 替换为runBlocking,应该会出现问题。 (如果没有剩下的代码,有点难以确定。)

【讨论】:

  • 我不建议使用runBlocking,因为顾名思义,您可能会阻止该线程上的其他操作。我会将该列表初始化为一个空列表,这样您就不会获得 NPE 并在该列表上添加一个观察者,这样您就可以在 DB fetch 之后获得正确的值。 (LiveData 也很酷)
  • 编辑后和我一起工作 suspend fun getPopular():List&lt;PopularResultsItem&gt;? { val client= RetrofitClient.getInstance().create(MoviesService::class.java).getPopular(API_KEY) if(client.isSuccessful){ Log.d("HomeViewModel lol",client.body().toString()) }else{ Log.e("HomeViewModel",client.message()) } return client.body()?.results }
猜你喜欢
  • 2015-09-08
  • 1970-01-01
  • 2019-11-25
  • 1970-01-01
  • 2014-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多