Last active
November 14, 2022 04:05
-
-
Save francescogatto/2ed6615c4387d87be7f658d53903c3d1 to your computer and use it in GitHub Desktop.
#KKD
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
suspend fun HttpClient.downloadFile(file: File, url: String): Flow<DownloadResult> { | |
return flow { | |
val response = call { | |
url(url) | |
method = HttpMethod.Get | |
}.response | |
val data = ByteArray(response.contentLength()!!.toInt()) | |
var offset = 0 | |
do { | |
val currentRead = response.content.readAvailable(data, offset, data.size) | |
offset += currentRead | |
val progress = (offset * 100f / data.size).roundToInt() | |
emit(DownloadResult.Progress(progress)) | |
} while (currentRead > 0) | |
response.close() | |
if (response.status.isSuccess()) { | |
file.writeBytes(data) | |
emit(DownloadResult.Success) | |
} else { | |
emit(DownloadResult.Error("File not downloaded")) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment