【问题标题】:How to replace blocking code for reading bytes in Kotlin如何替换阻塞代码以在 Kotlin 中读取字节
【发布时间】:2019-10-25 06:34:03
【问题描述】:

我有 ktor 应用程序,它需要来自 multipart 的文件,代码如下:

multipart.forEachPart { part ->
  when (part) {
    is PartData.FileItem -> {
      image = part.streamProvider().readAllBytes()
    }
    else -> // irrelevant
  }
}    

Intellij IDEA 将 readAllBytes() 标记为不适当的阻塞调用,因为 ktor 在协程之上运行。如何将此阻塞调用替换为适当的调用?

【问题讨论】:

    标签: kotlin kotlin-coroutines ktor


    【解决方案1】:

    考虑到 Ktor 作为非阻塞、暂停 IO 框架的声誉,我很惊讶 FileItem 显然除了阻塞 InputStream API 来检索它之外别无他物。鉴于此,您唯一的选择似乎是委托给 IO 调度程序:

    image = withContext(Dispatchers.IO) { part.streamProvider().readBytes() }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-13
      • 2018-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-15
      • 1970-01-01
      • 2020-02-12
      相关资源
      最近更新 更多