Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace blocking code for reading bytes in Kotlin

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?

like image 890
Izbassar Tolegen Avatar asked Jun 11 '26 11:06

Izbassar Tolegen


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() }
like image 163
Marko Topolnik Avatar answered Jun 14 '26 09:06

Marko Topolnik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!