Search code examples
androidkotlinviewmodelwrapper

How can I extract data from a wrapper class in my ViewModel (Kotlin)


I have created a DataState wrapper class to wrap data that I get from the Api Service I have. The class structure is the following

sealed class DataState<out R> {
    data class Success<out T>(val data: T): DataState<T>()
    data class Error(val exception: Exception): DataState<Nothing>()
    object Loading: DataState<Nothing>()
    object Empty: DataState<Nothing>()
}

I have a ViewModel class that I store the data and observe them from my Fragment or Activity. In my ViewModel I store the data like this

private val _dataList: MutableLiveData<DataState<List<CustomData>>> = MutableLiveData()
val dataList: LiveData<DataState<List<CustomData>>>
    get() = _dataList

then in my Activity I can observe the data when a change happens with success but the problem is when I want to access data already fetched in my ViewModel after a change has occurred.

when I call

 viewModel.dataList.value

the type that is returned is DataState<List> and I do not know how to get the actual list from that structure.


Solution

  • ViewModel is returning the state, you need to use when statement to get the respective data

    val dataState = viewModel.dataList.value
    
    when(dataState){
        is Success -> {
            val customerList = dataState.data 
           // you can access your list directly using data state
        }
        is Error -> {
            val error = dataState.exception   
        }
        //same applies for other states
    }