https://kotlinlang.org logo
#ktor
Title
# ktor
s

saket

07/18/2021, 4:30 AM
I’m trying to create an adapter between Okio and Ktor. Could someone be able to check if this piece of code for reading from a
ByteReadChannel
looks correct?
Copy code
private fun ByteReadChannel.source(): okio.Source {
  val channel = this
  return object : okio.Source {
    override fun read(sink: okio.Buffer, byteCount: Long): Long {
      if (byteCount == 0L) return 0L

      return runBlocking {
        if (!channel.isClosedForRead) {
          val bytes = channel.toByteArray(byteCount.toInt())
          sink.write(bytes)
          bytes.size.toLong()
        } else {
          -1. // Source is exhausted.
        }
      }
    }

    override fun close() = Unit // Couldn't find any way to close ByteReadChannel.
    override fun timeout() = Timeout.NONE
  }
}
👀 3
I'm not very familiar with coroutines, but that runBlocking call on every read does look expensive...
r

rnett

07/18/2021, 6:55 AM
You might have more luck in the okio issues or #squarelibraries. It doesn't look right but I'm not sure what the correct one would be
t

Thomas

07/18/2021, 12:19 PM
I am using the following in my project:
Copy code
channel.toInputStream().source()
With the following imports:
Copy code
import io.ktor.utils.io.jvm.javaio.toInputStream
import okio.source
s

saket

07/20/2021, 4:13 PM
@Thomas I unfortunately can’t use it in multiplatform code. @rnett this is useful, thank you!
👍🏻 1
162 Views