Skip to content

Commit 4c86bc1

Browse files
Chunk file cleanup work to respect Data size limit
1 parent e14ed7b commit 4c86bc1

File tree

1 file changed

+31
-1
lines changed

1 file changed

+31
-1
lines changed

app/src/main/kotlin/com/d4rk/cleaner/core/work/FileCleanWorkEnqueuer.kt

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package com.d4rk.cleaner.core.work
22

33
import android.app.Application
4+
import androidx.work.Data
45
import androidx.work.OneTimeWorkRequestBuilder
56
import androidx.work.WorkManager
67
import androidx.work.workDataOf
@@ -46,7 +47,7 @@ class FileCleanWorkEnqueuer(
4647
return Result.Error(IllegalArgumentException("No paths provided"))
4748
}
4849

49-
val chunks = paths.chunked(FileCleanupWorker.MAX_PATHS_PER_WORKER)
50+
val chunks = chunkPaths(paths, action)
5051
var continuation: androidx.work.WorkContinuation? = null
5152
val requestIds = mutableListOf<UUID>()
5253
for (chunk in chunks) {
@@ -72,5 +73,34 @@ class FileCleanWorkEnqueuer(
7273
Result.Error(t)
7374
}
7475
}
76+
77+
private fun chunkPaths(paths: Collection<String>, action: String): List<List<String>> {
78+
val result = mutableListOf<List<String>>()
79+
val current = mutableListOf<String>()
80+
for (path in paths) {
81+
current += path
82+
val tooBig = runCatching {
83+
Data.Builder()
84+
.putString(FileCleanupWorker.KEY_ACTION, action)
85+
.putStringArray(FileCleanupWorker.KEY_PATHS, current.toTypedArray())
86+
.build()
87+
.toByteArray()
88+
.size > Data.MAX_DATA_BYTES
89+
}.getOrDefault(true)
90+
val overLimit = current.size > FileCleanupWorker.MAX_PATHS_PER_WORKER
91+
if (tooBig || overLimit) {
92+
val last = current.removeAt(current.lastIndex)
93+
if (current.isNotEmpty()) {
94+
result += current.toList()
95+
}
96+
current.clear()
97+
current += last
98+
}
99+
}
100+
if (current.isNotEmpty()) {
101+
result += current.toList()
102+
}
103+
return result
104+
}
75105
}
76106

0 commit comments

Comments
 (0)