Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/visual-studio/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android kotlin中MutableLiveData中的泛型类型_Android_Kotlin_Generics_Android Livedata_Mutablelivedata - Fatal编程技术网

Android kotlin中MutableLiveData中的泛型类型

Android kotlin中MutableLiveData中的泛型类型,android,kotlin,generics,android-livedata,mutablelivedata,Android,Kotlin,Generics,Android Livedata,Mutablelivedata,我有一个val\u user:MutableLiveData问题是您试图将e类型为Throwable的赋值给List类型的参数 而不是 _user.postValue(Resource.Error("", e)) 您需要这样做: _user.postValue(Resource.Error(errorMessage, emptyList()) 或 其中errorMessage是e.message或类似的东西。为什么要创建一个新范围?您已经有了viewModelScope。

我有一个
val\u user:MutableLiveData问题是您试图将
e
类型为
Throwable
赋值给
List
类型的参数

而不是

_user.postValue(Resource.Error("", e))
您需要这样做:

_user.postValue(Resource.Error(errorMessage, emptyList())


其中
errorMessage
e.message
或类似的东西。

为什么要创建一个新范围?您已经有了
viewModelScope
。因为getUsers()是挂起函数,所以这不是答案,viewModelScope也是一个协同程序scope@EpicPandaForce你是说我应该使用viewModelScope.launch{}而不是CoroutineScope(IO+job!!).launch{}?我相信这确实是他的意思。使用此选项,您也不需要取消
onDestroy()
(或任何其他位置)中的作业,因为
viewModelScope
已绑定到
viewModel
的生命周期。谢谢您的回答,但在UI中,我如何知道错误的原因?如果是超时或其他网络问题。请将另一个参数添加到
资源
,使其成为
资源
。这样,您也可以传入Throwable(或任何其他内容)。
fun subScribeUI() {
        viewModel!!._user.observe(viewLifecycleOwner, Observer {
            it?.let {
               when(it.status) {
                   Status.LOADING -> {
                       Timber.d("LOADING")
                   }
                   Status.SUCCESS -> {
                       Timber.d("SUCCESS")
                   }
                   Status.ERROR -> {
                       Timber.d("ERROR")
                   }
               }
            }
        })
    }

       override fun onDestroyView() {
        super.onDestroyView()
viewModel?.cancelJob()
    }
_user.postValue(Resource.Error("", e))
_user.postValue(Resource.Error(errorMessage, emptyList())
_user.postValue(Resource.Error(errorMessage, null)