Skip to content

Instantly share code, notes, and snippets.

@stevepham
Last active December 25, 2020 15:30
Show Gist options
  • Save stevepham/b05c634e12effca76ae0e9b86d9247a8 to your computer and use it in GitHub Desktop.
Save stevepham/b05c634e12effca76ae0e9b86d9247a8 to your computer and use it in GitHub Desktop.
Download progress with ktor and flow
sealed class DownloadResult {
data class Progress(val progress: Int): DownloadResult()
object Success: DownloadResult()
data class Error(val message: String): DownloadResult()
}
suspend fun downloadFile(downloadedFile: File, url: String) = flow {
emit(Downloadresult.Progress(0))
val fos = downloadedFile.outputStream()
val bufSize = 4096
val buffer = ByteArray(bufSize)
var total = 0
val bytes = client.get<ByteReadChannel>(url)
while (true) {
val result = bytes.readAvailable(buffer, 0, bufSize)
if (result == -1) {
break
}
total += result
val progress = (total * 100 / fileSize).toInt()
emit(DownloadResult.Progress(progress))
fos.write(buffer)
fos.close()
emit(DownloadResult.Success)
}
}.distinctUntilChanged().flowOn(Dispatchers.IO)
@san-sk
Copy link

san-sk commented Dec 25, 2020

val fos = file.outputStream() -> in this 'file' where it comes from or could u tell how to use this

@stevepham
Copy link
Author

val fos = file.outputStream() -> in this 'file' where it comes from or could u tell how to use this
Sorry @san-sk, I wrote wrong name, 'file' is the file which you store download resource, I updated name to 'downloadFile' for clearer meaning

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