I want to create a data-receiver object which has ...
# ktor
t
I want to create a data-receiver object which has no dependencies on Ktor. That's why I translated the ByteReadChannel to a Flow using common-Kotlin. I don't have much experience in this area, so my question is: Is this method safe and is it the best way?
Copy code
suspend inline fun ByteReadChannel.toFlow(): Flow<ByteArray> {
    return flow {
        do {
            read { source, start, endExclusive ->
                val array = when {
                    endExclusive > start -> {
                        val mem = source.slice(start, endExclusive - start)
                        val byteArray = ByteArray(mem.size.toInt())
                        mem.copyTo(byteArray, 0, mem.size.toInt())
                        byteArray
                    }
                    else -> byteArrayOf()
                }

                emit(array)
                255
            }
            if (isClosedForRead) break
        } while (currentCoroutineContext().isActive)
    }
}
r
hi, couple of notes: 1. you don’t need to check for
currentCoroutineContext().isActive
, reading will be cancelled automatically if reader coroutine was cancelled 2. from read block you need to return actual number of bytes read 3. no need to slice memory, you can directly copy source to array in the end, your code should look like
Copy code
return flow {
  while (!channel.isClosedForRead) {
    channel.read { source, start, endExclusive ->
      val size = (endExclusive - start).toInt()
      val byteArray = ByteArray(size)
      source.copyTo(byteArray, start, size)
      emit(array)
      size
    }
  }
}
👍🏻 1
t
Thank you very much!