How to replace blocking code for reading bytes in Kotlin

Viewed 3026

I have ktor application which expects file from multipart in code like this:

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

The Intellij IDEA marks readAllBytes() as inappropriate blocking call since ktor operates on top of coroutines. How to replace this blocking call to the appropriate one?

1 Answers

Given the reputation of Ktor as a non-blocking, suspending IO framework, I was surprised that apparently for FileItem there is nothing else but the blocking InputStream API to retrieve it. Given that, your only option seems to be delegating to the IO dispatcher:

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