I have an app, where's an api call, which contains some data (which is stored in HashMap<String, Double>
), that I'd like to store in List
, and later on, push values of this list, to the database. Here is some logged response, from my ViewModel
:
Success(data={A=1.1, B=2.2 ... })
As you can see, the response is wrapped in generic class. I don't know how I can retrieve keys from this response. I feel like I've tried everything...
Generic class
sealed class RetrofitResult{
data class Success<out T>(val myData: T) : RetrofitResult()
data class Error(val myError: Throwable) : RetrofitResult()
}
Repository
suspend fun getData(): RetrofitResult{
return try {
val response = myApi.makeCall()
RetrofitResult.Success(myData= response.body()?.myHashMap)
} catch (exception: IOException) {
RetrofitResult.Error(error = exception.cause!!)
}
}
ViewModel
private val _dataStatus = MutableLiveData<RetrofitResult>()
val latestRates: LiveData<RetrofitResult> get() = _dataStatus
fun myData() {
viewModelScope.launch {
try {
val apiResponse = myRepository.getData()
_dataStatus .value = apiResponse
} catch (exception: IOException) {
//TODO
}
}
}
Now, I'd like to get keys from the response, and insert the in a List
, so I would have something like:
val dummyList: List<String> = listof("A", "B" ... )
You should push the generic type up to the sealed class super type, so that generic type can be in all the parameter and return types.
The Error type can specify that it satisfies Nothing
which is logically treated as the subtype of all types so you won't have to fool with specifying it when using individual instances of Error.
sealed class RetrofitResult<out T>{
data class Success<out T>(val myData: T) : RetrofitResult<T>()
data class Error(val myError: Throwable) : RetrofitResult<Nothing>()
}
Then you specify this type when working with the sealed class type:
suspend fun getData(): RetrofitResult<HashMap<String, Double>>{
//...
}
//...
private val _dataStatus = MutableLiveData<RetrofitResult<HashMap<String, Double>>>()
I specified a non-nullable data type. You need to handle the possible case of the body being null. Maybe turn that into an error.
I also recommend using Map
for your data type instead of HashMap
. HashMap is not only mutable, which is error-prone for using in a LiveData or Flow, but also it is an oddly specific subtype of MutableMap for no reason.