Skip to content

Instantly share code, notes, and snippets.

@francescogatto
Last active November 14, 2022 04:05
Show Gist options
  • Save francescogatto/2ed6615c4387d87be7f658d53903c3d1 to your computer and use it in GitHub Desktop.
Save francescogatto/2ed6615c4387d87be7f658d53903c3d1 to your computer and use it in GitHub Desktop.
#KKD
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