Skip to content

Commit 9b11da8

Browse files
committed
[storage] Prevent duplicate observer registration in TransferWorkerObserver to mitigate OOM (#2840)
1 parent f567b4b commit 9b11da8

File tree

1 file changed

+7
-0
lines changed

1 file changed

+7
-0
lines changed

aws-storage-s3/src/main/java/com/amplifyframework/storage/s3/transfer/TransferWorkerObserver.kt

+7
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ import kotlinx.coroutines.Dispatchers
3131
import kotlinx.coroutines.asCoroutineDispatcher
3232
import kotlinx.coroutines.launch
3333
import kotlinx.coroutines.withContext
34+
import java.util.concurrent.ConcurrentHashMap
3435

3536
internal class TransferWorkerObserver private constructor(
3637
context: Context,
@@ -49,6 +50,9 @@ internal class TransferWorkerObserver private constructor(
4950
AWSS3StoragePlugin.AWS_S3_STORAGE_LOG_NAMESPACE.format(this::class.java.simpleName)
5051
)
5152

53+
private val observedTags =
54+
ConcurrentHashMap.newKeySet<String>()
55+
5256
init {
5357
attachObserverForPendingTransfer()
5458
}
@@ -195,15 +199,18 @@ internal class TransferWorkerObserver private constructor(
195199

196200
private suspend fun attachObserver(tag: String) {
197201
withContext(Dispatchers.Main) {
202+
if (observedTags.contains(tag)) return@withContext
198203
val liveData = workManager.getWorkInfosByTagLiveData(tag)
199204
liveData.observeForever(this@TransferWorkerObserver)
200205
}
201206
}
202207

203208
private suspend fun removeObserver(tag: String) {
204209
withContext(Dispatchers.Main) {
210+
if (!observedTags.contains(tag)) return@withContext
205211
workManager.getWorkInfosByTagLiveData(tag)
206212
.removeObserver(this@TransferWorkerObserver)
213+
observedTags.remove(tag)
207214
}
208215
}
209216
}

0 commit comments

Comments
 (0)