gpt4 book ai didi

kotlin - 如何使用超时值同步调用异步请求?

转载 作者:行者123 更新时间:2023-12-04 03:43:05 25 4
gpt4 key购买 nike

我必须同步调用异步 api 请求。由于此 api 请求需要很长时间才能回答,我还想设置一个超时以使 api 请求失败并继续 null。这是我调用此 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()
}
}
}

我无法更改 External3rdPartyApi 的工作方式。

我认为上面的代码看起来很糟糕。另外,我读了 another answer :

withTimeout { ... } is designed to cancel the ongoing operation on timeout, which is only possible if the operation in question is cancellable.

那么,我应该使用 suspendCancellableCoroutine 而不是 suspendCoroutine 吗?

我怎样才能写得更好?

最佳答案

如果您不能(或不想)处理协程的取消,则使用 suspendCoroutine 没问题。但是因为你有超时,你应该考虑使用 suspendCancellableCoroutine并处理取消事件以停止工作(在第三方功能中 - 如果可以的话)。

suspendCancellableCoroutine<T> { continuation ->
continuation.invokeOnCancellation { throwable ->
// now you could stop your (third party) work
}
}

当您的第三方函数抛出异常时,您可以 try catch 它并使用 exception 恢复或返回 null 值(取决于您的用例):

suspendCancellableCoroutine<T?> { continuation ->
try {
continuation.resume(thirdParty.call())
} catch (e: Exception) {
// resume with exception
continuation.resumeWithException(e)
// or just return null and swallow the exception
continuation.resume(null)
}
}

让我们把所有的放在一起

suspend fun call(): Response? = withContext(Dispatchers.IO) {
return@withContext withTimeoutOrNull(1000L) {
return@withTimeoutOrNull suspendCancellableCoroutine { continuation ->
try {
continuation.resume(External3rdPartyApi.newRequest(accessStage))
} catch (e: Exception) {
// resume with exception
continuation.resumeWithException(e)

// or just return null and swallow the exception
continuation.resume(null)
}

// in case the coroutine gets cancelled - because of timeout or something else
continuation.invokeOnCancellation {
// stop all the work
}
}
}
}

关于kotlin - 如何使用超时值同步调用异步请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65610573/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com