DownloadWorker: Better handle individual file progress updates

* Don't filter InputStream updates as we are already guarding UI updates against total progress
* Update downloadedBytes based on bytesCopied to reflect real progress
* Use collect instead of collectLatest to ensure all updates from flow are handled

Signed-off-by: Aayush Gupta <aayushgupta219@gmail.com>
This commit is contained in:
Aayush Gupta
2024-05-06 12:58:59 +05:30
parent 855bb1dbc8
commit 00532f200e
2 changed files with 7 additions and 11 deletions

View File

@@ -7,7 +7,6 @@ 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<DownloadInfo> {
@@ -29,9 +28,9 @@ fun InputStream.copyTo(out: OutputStream, streamSize: Long): Flow<DownloadInfo>
out.write(buffer, 0, bytes)
bytesCopied += bytes
// Emit stream progress in percentage
emit(DownloadInfo((bytesCopied * 100 / streamSize).toInt(), bytesCopied, speed))
emit(DownloadInfo((bytesCopied * 100 / streamSize).toInt(), bytes.toLong(), speed))
bytes = read(buffer)
}
timer.cancel()
}.flowOn(Dispatchers.IO).distinctUntilChangedBy { it.progress }
}.flowOn(Dispatchers.IO)
}