architecture-samples icon indicating copy to clipboard operation
architecture-samples copied to clipboard

[todo‑mvp‑rxjava] What is the purpose of setLoadingIndicator() need to check getView() is null or not

Open hvsimon opened this issue 7 years ago • 1 comments

I guess it can prevent the async call setLoadingIndicator() when view was destroy. But in todo‑mvp‑rxjava, the async call would be dispose when view on pause. Is it necessary to check view is null or not ?

hvsimon avatar Jun 29 '18 01:06 hvsimon

Suggested Response: Great observation — this is an important subtlety in MVP + RxJava implementations!

Why check getView() != null before calling setLoadingIndicator()? You're right — ideally, if Rx subscriptions are properly disposed in onPause() or onStop(), we shouldn't receive emissions when the view is detached.

But here's why the null check is still commonly done:

  1. Defensive Programming Even with disposables, in rare cases (like long-running emissions or mismanaged subscriptions), the Presenter may still try to update a null view. This null check prevents crashes due to NullPointerException.

if (getView() != null) { getView().setLoadingIndicator(true); } It’s a safety net — especially when code is modified, reused, or extended.

  1. Lifecycle Races In some edge cases, like:

Async calls racing with onPause()

View being destroyed before Rx emission arrives

…it’s possible the view is already null when the callback hits.

So even if we dispose correctly, the null check guards against race conditions.

  1. Code Clarity It also documents intent — telling future devs: “Hey, this might be async and the view might not be here anymore.”

Is it strictly necessary? If:

All Rx subscriptions are properly disposed

You’re 100% confident in view lifecycle handling Then no, it's not strictly necessary.

But in practice, most projects include the null check as a best practice — it's low-cost and adds robustness.

VaradGupta23 avatar Aug 06 '25 04:08 VaradGupta23