Created
November 26, 2018 00:50
-
-
Save naddeoa/4172e84aca533319a1cc5663d2fab39e to your computer and use it in GitHub Desktop.
Copy input stream in Kotlin with progress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Cool
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
Thanks.