Last active
December 25, 2020 15:30
-
-
Save stevepham/b05c634e12effca76ae0e9b86d9247a8 to your computer and use it in GitHub Desktop.
Download progress with ktor and flow
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
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) |
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
val fos = file.outputStream() -> in this 'file' where it comes from or could u tell how to use this