如何重写代码以使用 Kotlin 的 kotlinx-coroutines-jdk8?



如何使用Kotlin-jdk异步函数重写此代码以避免错误"悬架函数只能在协程体";?

var result: CompletableFuture<CarInfoDto>? = null
try {
result = CompletableFuture.supplyAsync {
runBlocking {
myService.getCarInfo(carId)  //**"Suspension functions can be called only within coroutine body"**
}
}
return ResponseEntity(future?.get(1000, TimeUnit.MILLISECONDS), HttpStatus.OK)
} catch (timeoutException: TimeoutException) {

当前代码中的get()调用会阻止当前线程等待异步作业,因此启动此异步作业没有任何好处,您可以简单地调用runBlocking(如果您确实对超时感兴趣,则使用withTimeout(:

try {
val result = runBlocking {
withTimeout(1000) {
myService.getCarInfo(carId)
}
}
return ResponseEntity(result, HttpStatus.OK)
} catch (timeoutException: TimeoutException) {
...
}

然而,由于您似乎在使用Spring,因此应该能够使控制器函数成为suspend函数,并且可能根本不需要创建新的协程或块(只需调用getCarInfo()方法(。

最新更新