简体   繁体   English

kotlin 中的 MutableLiveData 中的泛型类型

[英]Generic type in MutableLiveData in kotlin

I have a val _user: MutableLiveData<Resource<List<ApiUser>>> = MutableLiveData() in viewmodel but i want to postValue errorException我在视图模型中有一个val _user: MutableLiveData<Resource<List<ApiUser>>> = MutableLiveData()但我想 postValue errorException

在此处输入图像描述

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

//Fragment //分段

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()
    }

The problem is that you are trying to assign e , which is of type Throwable to argument of type List<ApiUser> .问题是您正在尝试将类型为Throwablee分配给List<ApiUser>类型的参数。

Instead of代替

_user.postValue(Resource.Error("", e))

you need to do this:你需要这样做:

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

or或者

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

where errorMessage is e.message or something similar.其中errorMessagee.message或类似的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM