https://kotlinlang.org logo
Title
j

Jan

04/13/2023, 9:33 PM
Hey quick question: I'm uploading to an API using chunks and that is my code reading from a ByteReadChannel and reading from it in chunks:
val limit = min(chunkSize, size.toInt() - offset) //the max chunk size or the remaining bytes
val buffer = ByteArray(limit.toInt()) //buffer
val read = dataStream.readAvailable(buffer, 0, limit.toInt()) //read from the stream
The problem with this is that read is often way smaller than the "limit" so I'm using this instead:
val limit = min(chunkSize, size.toInt() - offset)
val buffer = ByteArray(limit.toInt())
var totalRead = 0
var read: Int

while (totalRead < limit.toInt()) {
    read = dataStream.readAvailable(buffer, totalRead, limit.toInt() - totalRead)
    if (read == -1) {
         break
    }
    totalRead += read
}
Is that the best way or is there another?
r

Rustam Siniukov

04/17/2023, 10:04 AM
if you need to fill whole byte array, it’s better to use
readFully
instead