Priyank Jain
03/05/2021, 8:40 AMinline fun <reified O> getAPIResult(apiResponse: BaseResponseModel<O>): O? {
val actualResult: O? = try {
when (O::class.java) {
List::class.java -> {
apiResponse.getResponseModel(object : TypeToken<List<O>>() {}.type)
}
ArrayList::class.java -> {
apiResponse.getResponseModel(object : TypeToken<ArrayList<O>>() {}.type)
}
else -> {
apiResponse.getResponseModel(O::class.java)
}
}
} catch (e: Exception) {
null
}
return actualResult
}
mkrussel
03/05/2021, 12:59 PM0
is still going to be resolved at compile time and not runtime, so if you are calling it with O
being Any
it will go to the else.
Since it is all resolved at compile time, it would make more sense to just have three different methods. The last case makes some sense to be inline with reified types.mkrussel
03/05/2021, 1:09 PMO
is a List
, you will be doing something like TypeToken<List<List<*>>()
Priyank Jain
03/06/2021, 2:51 PMinline fun <reified O> fetchDataFromAPI(
crossinline apiMethod: suspend () -> BaseResponseModel<O>
): Flow<APIResult<O>> {
return flow {
emit(APIResult.loading<O>())
if (Utils.isNetworkAvailable()) {
try {
val response = apiMethod.invoke()
emit(getAPIResult(response))
} catch (e: Exception) {
APIResult.error(null, e.message ?: "")
}
} else {
emit(APIResult.noNetwork<O>())
}
}.flowOn(<http://Dispatchers.IO|Dispatchers.IO>)
}
And the API method I am passing is to this inline function is like this, it is a retrofit interface method.
suspend fun getAllCity() : List<City>
So is there any solution to this problem?