我在viewmodel中有一个val _user: MutableLiveData<Resource<List<ApiUser>>> = MutableLiveData(),但我想发布valueErrorException
android - Kotlin中MutableLiveData中的泛型类型-LMLPHP

  // A generic class that contains data and status about loading this data.
    sealed class Resource<T>(
        val data: T? = null,
        val message: String? = null
    ) {
        class Success<T>(data: T) : Resource<T>(data)
        class Loading<T>(data: T? = null) : Resource<T>(data)
        class Error<T>(message: String, data: T? = null) : Resource<T>(data, message)
    }
// ViewModel
class HomeViewModel : ViewModel() {

        val _user: MutableLiveData<Resource<List<ApiUser>>> = MutableLiveData()
        var job: CompletableJob? = null
        fun f() {
            job = Job()
            _user.postValue(Resource.Loading(null))
            CoroutineScope(IO+job!!).launch {
                try {
                    _user.postValue(Resource.Success(RetrofitBuilder.apiService.getUsers()))
                } catch (e: Throwable) {
                    _user.postValue(Resource.Error("",e))
                }
            }
        }
     fun cancelJob() {
            job?.cancel()
        }

    }
//分段
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()
    }

最佳答案

问题是您正在尝试将e类型的Throwable分配给List<ApiUser>类型的参数。
代替

_user.postValue(Resource.Error("", e))
您需要这样做:
_user.postValue(Resource.Error(errorMessage, emptyList())
要么
_user.postValue(Resource.Error(errorMessage, null)
其中errorMessagee.message或类似名称。

关于android - Kotlin中MutableLiveData中的泛型类型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/63230470/

10-08 21:49