DownloadWorker: Progress improvements

* Handle split apk download progress
* Also share download speed and time remaining

Signed-off-by: Aayush Gupta <aayushgupta219@gmail.com>
This commit is contained in:
Aayush Gupta
2023-11-06 20:40:54 +05:30
parent 5b60758347
commit 0f4021117f
3 changed files with 57 additions and 8 deletions

View File

@@ -1,24 +1,37 @@
package com.aurora.extensions
import com.aurora.store.data.model.DownloadInfo
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import java.io.InputStream
import java.io.OutputStream
import kotlinx.coroutines.flow.distinctUntilChangedBy
import kotlin.concurrent.fixedRateTimer
fun InputStream.copyTo(out: OutputStream, streamSize: Long): Flow<Int> {
fun InputStream.copyTo(out: OutputStream, streamSize: Long): Flow<DownloadInfo> {
return flow {
var bytesCopied: Long = 0
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
var bytes = read(buffer)
var lastTotalBytesRead = 0L
var speed: Long = 0
@Suppress("KotlinConstantConditions") // False-positive for bytesCopied always being zero
val timer = fixedRateTimer("timer", true, 0L, 1000) {
val totalBytesRead = bytesCopied
speed = totalBytesRead - lastTotalBytesRead
lastTotalBytesRead = totalBytesRead
}
while (bytes >= 0) {
out.write(buffer, 0, bytes)
bytesCopied += bytes
bytes = read(buffer)
// Emit stream progress in percentage
emit((bytesCopied * 100 / streamSize).toInt())
emit(DownloadInfo((bytesCopied * 100 / streamSize).toInt(), bytesCopied, speed))
bytes = read(buffer)
}
}.flowOn(Dispatchers.IO).distinctUntilChanged()
timer.cancel()
}.flowOn(Dispatchers.IO).distinctUntilChangedBy { it.progress }
}