Mitigation Strategy: Robust Subscription Management with CompositeDisposable
Description:
- Initialization: In each Activity or Fragment that uses RxJava subscriptions, declare a
CompositeDisposable
instance variable:private val compositeDisposable = CompositeDisposable()
. - Subscription Handling: Whenever you subscribe to an
Observable
orFlowable
(using.subscribe()
), immediately add the returnedDisposable
to thecompositeDisposable
:compositeDisposable.add(myObservable.subscribe(...))
. - Disposal: In the
onDestroy()
method of your Activity or Fragment (oronStop()
if appropriate), callcompositeDisposable.clear()
. This unsubscribes from all active subscriptions, preventing leaks. If you might resubscribe inonStart()
, useclear()
; otherwise, usedispose()
to prevent further additions. - Consistency: Ensure this pattern is consistently applied across all Activities and Fragments that use RxJava.
List of Threats Mitigated:
- Resource Leaks (Memory, CPU, Battery, Network): Severity: High. Unintentional background operations can consume significant resources.
- Data Inconsistency: Severity: Medium to High. Background operations modifying shared state after UI destruction.
- Unintentional Denial of Service (DoS): Severity: Medium. Resource exhaustion making the application unusable.
Impact:
- Resource Leaks: Risk significantly reduced (close to eliminated if implemented consistently).
- Data Inconsistency: Risk significantly reduced.
- Unintentional DoS: Risk significantly reduced.
Currently Implemented:
- Example:
MainActivity.kt
,MyFragment.kt
(usingcompositeDisposable.clear()
inonDestroy()
). - (Fill in with your project details.)
Missing Implementation:
- Example:
NetworkDataFragment.kt
(using individualDisposable
variables). - (Fill in with your project details.)
Mitigation Strategy: Correct Threading with subscribeOn and observeOn
Description:
- Background Operations: Use
subscribeOn()
to specify the thread for the source Observable's work. For network/database/heavy computations, useSchedulers.io()
orSchedulers.computation()
. Example:myNetworkObservable.subscribeOn(Schedulers.io())
. - UI Updates: Use
observeOn(AndroidSchedulers.mainThread())
to switch to the main thread only for UI updates, after background work. Example:.observeOn(AndroidSchedulers.mainThread())
. - Avoid Long Operations on Main Thread: Code after
observeOn(AndroidSchedulers.mainThread())
must be fast and non-blocking. Chain anothersubscribeOn()
if needed. - Granularity: Break down large tasks using operators like
flatMap
,concatMap
, orswitchMap
.
List of Threats Mitigated:
- UI Freezes/ANRs (Application Not Responding): Severity: High. Blocking the main thread.
- CalledFromWrongThreadException: Severity: High. Updating UI from a background thread.
Impact:
- UI Freezes/ANRs: Risk significantly reduced.
- CalledFromWrongThreadException: Risk eliminated.
Currently Implemented:
- Example:
UserRepository.kt
(correctsubscribeOn
andobserveOn
usage). - (Fill in with your project details.)
Missing Implementation:
- Example:
ImageProcessingService.kt
(image manipulation on the main thread). - (Fill in with your project details.)
Mitigation Strategy: Comprehensive Error Handling
Description:
- onError Handler: In every
subscribe()
call, provide anonError
handler (lambda or method reference) to handle errors. At minimum, log the error. - User Feedback: In the
onError
handler, consider displaying an error message to the user. - Retry Logic: For transient errors, use
retry()
orretryWhen()
for automatic retries.retryWhen
allows complex strategies (e.g., exponential backoff). - Error Recovery: Use
onErrorResumeNext
to switch to a different Observable, oronErrorReturn
to emit a default value. - Global Error Handler (Limited Use): Set a global handler with
RxJavaPlugins.setErrorHandler()
. Use this only for logging unhandled errors and a generic error message. Avoid complex logic.
List of Threats Mitigated:
- Unhandled Exceptions (Crashes): Severity: High. Unhandled errors crash the app.
- Unexpected Application State: Severity: Medium. Errors can lead to inconsistency.
- Poor User Experience: Severity: Medium. No information about errors.
Impact:
- Unhandled Exceptions: Risk significantly reduced.
- Unexpected Application State: Risk reduced.
- Poor User Experience: Risk reduced.
Currently Implemented:
- Example:
NetworkService.kt
(usingonError
,retry(3)
). - (Fill in with your project details.)
Missing Implementation:
- Example:
DatabaseHelper.kt
(missingonError
handlers). - (Fill in with your project details.)
Mitigation Strategy: Backpressure Handling (If Applicable)
Description:
- Identify Potential Backpressure: Check if any Observables emit items faster than consumption. Likely with fast data sources (sensors, network streams).
- Use Flowable: If backpressure is a concern, use
Flowable
instead ofObservable
.Flowable
is designed for this. - Choose a Backpressure Strategy: When creating a
Flowable
, specify aBackpressureStrategy
:BackpressureStrategy.BUFFER
: Buffers items (risk ofOutOfMemoryError
).BackpressureStrategy.DROP
: Drops oldest items.BackpressureStrategy.LATEST
: Drops all but the most recent item.BackpressureStrategy.ERROR
: SignalsMissingBackpressureException
.BackpressureStrategy.MISSING
: No strategy; relies on downstream operators.
- Operators: Use
onBackpressureBuffer
,onBackpressureDrop
, oronBackpressureLatest
on an existingObservable
. - Windowing/Buffering: Consider
window
,buffer
, orsample
to reduce emission rate.
List of Threats Mitigated:
- MissingBackpressureException: Severity: High. Crashes the application.
- OutOfMemoryError: Severity: High. Unbounded buffering.
- Data Loss: Severity: Medium (depending on strategy).
DROP
andLATEST
lose data.
Impact:
- MissingBackpressureException: Risk eliminated.
- OutOfMemoryError: Risk significantly reduced.
- Data Loss: Risk managed (but potentially present).
Currently Implemented:
- Example:
SensorDataManager.kt
(usingFlowable
,BackpressureStrategy.LATEST
). - (Fill in with your project details.)
Missing Implementation:
- Example:
NetworkStreamProcessor.kt
(usingObservable
without backpressure handling). - (Fill in with your project details.)