1

I have a val _user: MutableLiveData<Resource<List<ApiUser>>> = MutableLiveData()in viewmodel but i want to postValue errorException

enter image description here

  // 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()
    }
Mansukh Ahir
  • 3,373
  • 5
  • 40
  • 66

1 Answers1

1

The problem is that you are trying to assign e, which is of type Throwable to argument of type 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.

Primož Ivančič
  • 1,984
  • 1
  • 17
  • 29