I’m trying to create an adapter between Okio and K...
# ktor
s
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
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
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
@Thomas I unfortunately can’t use it in multiplatform code. @rnett this is useful, thank you!
👍🏻 1
239 Views