Skip to content

Instantly share code, notes, and snippets.

@naddeoa
Created November 26, 2018 00:50
Show Gist options
  • Save naddeoa/4172e84aca533319a1cc5663d2fab39e to your computer and use it in GitHub Desktop.
Save naddeoa/4172e84aca533319a1cc5663d2fab39e to your computer and use it in GitHub Desktop.
Copy input stream in Kotlin with progress
import java.io.InputStream
import java.io.OutputStream
fun InputStream.copyTo(out: OutputStream, onCopy: (totalBytesCopied: Long, bytesJustCopied: Int) -> Any): Long {
var bytesCopied: Long = 0
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
var bytes = read(buffer)
while (bytes >= 0) {
out.write(buffer, 0, bytes)
bytesCopied += bytes
onCopy(bytesCopied, bytes)
bytes = read(buffer)
}
return bytesCopied
}
@doodla
Copy link

doodla commented Apr 27, 2019

Thanks.

@mwiede
Copy link

mwiede commented Oct 21, 2019

Cool

@theimpulson
Copy link

In case this helps someone, here is the version using Flow emitting progress in percentage:

fun InputStream.copyTo(out: OutputStream, streamSize: Long): Flow<Int> {
    return flow {
        var bytesCopied: Long = 0
        val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
        var bytes = read(buffer)
        while (bytes >= 0) {
            out.write(buffer, 0, bytes)
            bytesCopied += bytes
            // Emit stream progress in percentage
            emit((bytesCopied * 100 / streamSize).toInt())
            bytes = read(buffer)
        }
    }.flowOn(Dispatchers.IO).distinctUntilChanged()
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment