Code changes applied.
I followed a guide on how to create a kotlin coroutine and do network request and ended up with:
suspend fun <T : Any> safeApiCall(call: suspend () -> Response<T>): ApiResult<T> {
return safeApiResult(call)
}
private suspend fun <T: Any> safeApiResult(call: suspend ()-> Response<T>) : ApiResult<T>{
val response = call.invoke()
return if (response.isSuccessful) {
val body = response.body()
if (body == null) {
ApiResult.Error(response.code())
} else {
ApiResult.Success(body)
}
} else {
ApiResult.Error(response.code())
}
}
suspend fun getSnappedPoints(path: String): ApiResult<SnappedPointsData> {
return safeApiCall(
call = { googleRoadsService.getSnappedPoints(path).await()}
)
}
and calling the network request looks like this:
private fun getSnappedPoints() {
val paths = Utils.getPathFromLocations(locations)
CoroutineScope(Dispatchers.IO).launch {
val results = paths.map {
async { googleRoadsRepository.getSnappedPoints(it) }
}.awaitAll()
Timber.i("results: ${results.size}")
val snappedPoints = ArrayList<LocationSnap>()
results.forEach {
if (it is ApiResult.Success) {
snappedPoints.addAll(it.data.snappedPoints)
}
}
withContext(Dispatchers.Main) {
if (snappedPoints.isNotEmpty()) {
drawPolyline(snappedPoints)
} else {
showError()
}
}
}
}
Current problem:
The function getSnappedPoints() is called when I click on specific item. For the very first time it actually calls google API and result is > 0 (size), but if I go back and click second time on the same/other item, getSnappedPoints() is called, paths is not Empty, but somehow it does not call googleRoadsRepository.getSnappedPoints(it) and kinda skips that step in debug and all I can see is that result is always 0. What could cause this?
Repository.getPoints()? It has a parameter while thegetPointsshown in the question has no argument. What is result2 in this context here? which type of if condition is this?