[Bug]: Uncleared CompositeDisposable in @Singleton UploadClient causes memory leak
Summary
UploadClient is an application-level @Singleton managed by Dagger. It maintains a shared CompositeDisposable:
private val compositeDisposable = CompositeDisposable()
Subscriptions for every uploaded file chunk are added to this collection at lines 87 and 173.
Root Cause
1. Disposable Retention
RxJava does not automatically remove completed subscriptions from a CompositeDisposable. Since cleanup only occurs in a narrow branch at line 91, completed observers can remain retained by the singleton, along with references to upload workers, contributions, and media-related objects.
Repeated uploads can therefore increase memory usage over time.
2. Cross-Upload Cancellation
compositeDisposable.clear()
The collection is shared across all uploads. Clearing it for one missing contribution can also cancel subscriptions belonging to other active uploads.
Affected Files
app/src/main/java/fr/free/nrw/commons/upload/UploadClient.kt(Lines 51, 87, 91, 173–196)
Steps to Reproduce
- Upload multiple photos or a large file split into chunks.
- Repeat uploads and allow them to complete.
- Inspect
UploadClient.compositeDisposableusing Android Studio Memory Profiler. - Check for retained completed observers and their captured references.
Expected Behaviour
- Subscriptions should be scoped to individual uploads.
- Completed, failed, and cancelled subscriptions should be cleaned up.
- Cancelling one upload should not affect other active uploads.
Actual Behaviour
- Completed subscriptions remain referenced by the singleton's
CompositeDisposable. - Repeated uploads can increase memory retention and memory pressure.
- Clearing the shared collection can interrupt unrelated uploads.
Proposed Solution
-
Remove the class-level shared
CompositeDisposablefrom the@Singleton UploadClient. -
Scope subscriptions to individual upload operations:
- Track active disposables separately for each upload operation using an appropriate thread-safe collection.
- Ensure each upload has independent disposable management.
- Clean up its disposable set when the upload completes, fails, or is cancelled, using
doFinallyor equivalent lifecycle handling. - Ensure cleanup for one upload does not affect other concurrent uploads.
-
Add unit tests in
UploadClientTest.ktto verify disposable cleanup and ensure cancelling one upload does not affect another.