Skip to content

Commit 886783d

Browse files
authored
Reduce frequency of file download progress updates (#6984)
Task/Issue URL: https://app.asana.com/1/137249556945/project/1202552961248957/task/1211712368005490?focus=true ### Description This PR updates file downloader to avoid emitting excessive number of progress updates, which can have a negative impact on download performance. ### Steps to test this PR - [x] Smoke test downloading files, focusing on large downloads (>100MB). See #6958 for some examples. - [x] Verify progress is displayed correctly in the system notification. ### No UI changes
1 parent 3a45dda commit 886783d

File tree

1 file changed

+16
-7
lines changed

1 file changed

+16
-7
lines changed

downloads/downloads-impl/src/main/java/com/duckduckgo/downloads/impl/UrlFileDownloader.kt

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -117,24 +117,33 @@ class UrlFileDownloader @Inject constructor(
117117
): Boolean {
118118
logcat { "Writing streaming response body to disk $fileName" }
119119

120-
// ensure content length never 0
121-
val contentLength = if (body.contentLength() > 0) body.contentLength() else -1
120+
val contentLength = body.contentLength().takeIf { it > 0 }
121+
val calculateProgress: (Long) -> Int = if (contentLength != null) {
122+
// Calculate real progress when content length is known
123+
{ bytesWritten -> (bytesWritten * 100 / contentLength).toInt() }
124+
} else {
125+
// Calculate fake progress when content length is not known
126+
var progressSteps = 0.0
127+
{ floor(calculateFakeProgress(progressSteps) * 100.0).toInt().also { progressSteps += 0.0001 } }
128+
}
129+
122130
val file = directory.getOrCreate(fileName)
123131
val sink = file.sink()
124132
val source = body.source()
125133

126134
var totalRead = 0L
127135
val buffer = Buffer()
128136
val success = try {
129-
var progressSteps = 0.0
137+
var progress = 0
130138
while (!source.exhausted()) {
131139
val didRead = source.read(buffer, READ_SIZE_BYTES)
132140
totalRead += didRead
133141
sink.write(buffer, didRead)
134-
val fakeProgress = floor(calculateFakeProgress(progressSteps) * 100.0).toInt().also { progressSteps += 0.0001 }
135-
val calculatedProgress = (totalRead * 100 / contentLength)
136-
val progress = if (calculatedProgress < 0L) fakeProgress else calculatedProgress
137-
downloadCallback.onProgress(downloadId, fileName, progress.toInt())
142+
val newProgress = calculateProgress(totalRead)
143+
if (newProgress != progress) {
144+
progress = newProgress
145+
downloadCallback.onProgress(downloadId, fileName, progress)
146+
}
138147
}
139148
true
140149
} catch (t: Throwable) {

0 commit comments

Comments
 (0)