【问题标题】:How to rewrite the code to use Kotlin's kotlinx-coroutines-jdk8?如何重写代码以使用 Kotlin 的 kotlinx-coroutines-jdk8?
【发布时间】:2021-01-26 23:32:56
【问题描述】:

如何使用 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) {

【问题讨论】:

    标签: kotlin asynchronous


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2018-07-15
      • 1970-01-01
      • 2021-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-22
      相关资源
      最近更新 更多