首页 > 解决方案 > How to rewrite the code to use Kotlin's kotlinx-coroutines-jdk8?

问题描述

How to rewrite this code using Kotlin jdk async functions to avoid the error "Suspension functions can be called only within coroutine body"?

    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) {

标签: kotlinasynchronous

解决方案


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

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

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


推荐阅读