我知道AsyncRestTemplate已经被弃用了,但不管怎样。我写这样的代码把AsyncRestTemplate和协程结合在一起,这样做对吗?
suspend fun dodo(url: URL): String {
val result = AsyncRestTemplate().getForEntity(url, String::class.java)
return result.awaitBody()
}
suspend fun <T> ListenableFuture<ResponseEntity<T>>.awaitBody(): T {
while (this.isDone.not)
yield()
return this.get().body!!
}发布于 2020-04-07 07:04:02
您的代码是正确的,但效率很低,因为它实际上是一个重复调用ListenableFuture.isDone直到完成的忙等待循环。
当您需要在异步API和挂起函数之间进行转换时,请使用提供的回调API:
suspend fun <T> ListenableFuture<T>.await(): T = suspendCancellableCoroutine { cont ->
// Special handling for Future<*> objects
cont.cancelFutureOnCancellation(this)
addCallback(object : ListenableFutureCallback<T> {
override fun onFailure(ex: Throwable) {
cont.resumeWithException(ex)
}
override fun onSuccess(result: T) {
cont.resume(result)
}
})
}这不会浪费时间检查将来是否完成,而只是在结果实际可用时告诉将来恢复挂起的函数。
https://stackoverflow.com/questions/61069589
复制相似问题