我想通过一个Flow来观察下载进度,所以写了一个这样的函数:
suspend fun downloadFile(file: File, url: String): Flow<Int>{
val client = HttpClient(Android)
return flow{
val httpResponse: HttpResponse = client.get(url) {
onDownload { bytesSentTotal, contentLength ->
val progress = (bytesSentTotal * 100f / contentLength).roundToInt()
emit(progress)
}
}
val responseBody: ByteArray = httpResponse.receive()
file.writeBytes(responseBody)
}
}
但onDownload
只会调用一次,并且不会下载文件。如果我删除 emit(progress)
它会起作用。
io.ktor:ktor-client-android:1.6.7