I have to synchronously call an asynchronous api request. Since this api request takes long time to answer, I also want to set a timeout to fail the api-request and continue with null. Here's my code to call this api:
private suspend fun call(
accessStage: AccessStage,
): Response? = withContext<Response?>(Dispatchers.IO) {
return@withContext withTimeoutOrNull(1000) {
suspendCoroutine<Response?> { continuation ->
val request = External3rdPartyApi.newRequest(
accessStage
) { response, throwable ->
continuation.resume(response)
}
request.parameters = hashMapOf<String, String>().apply {
put["token"] = External3rdPartyApi.TOKEN
put["salt"] = External3rdPartyApi.calculateSalt(accessStage)
}
request.executeAsync()
}
}
}
I can't change how External3rdPartyApi
works.
I think above code looks evil. Also, I read in another answer:
withTimeout { ... }
is designed to cancel the ongoing operation on timeout, which is only possible if the operation in question is cancellable.
So, should I use suspendCancellableCoroutine
instead of suspendCoroutine
?
How can I write it in a better way?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…