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

mPresenter.takeView(this); onResume

Open bensanpast opened this issue 7 years ago • 1 comments

why “mPresenter.takeView(this);” worked onResume,not onCreate?Doesn't this do a lot of repetitive work?

bensanpast avatar Jul 06 '18 01:07 bensanpast

Suggested Response: Great question — and you're absolutely right to wonder about this.

Why is mPresenter.takeView(this) called in onResume() and not onCreate()? The reason has to do with lifecycle awareness and view availability in the MVP pattern (Model-View-Presenter).

Key Concepts: In MVP, the Presenter needs a reference to the View (usually an Activity or Fragment).

takeView(this) is how we attach the view to the presenter.

This is usually balanced with dropView() in onPause() or onStop() to prevent memory leaks.

Why onResume()? onResume() is called every time the Activity or Fragment becomes visible again.

If takeView() were only called in onCreate(), the presenter would not be re-attached if the user navigated away and then returned (e.g. through back stack or screen rotation).

Calling it in onResume() ensures that the presenter always has a valid view reference.

Is it repetitive? Yes — but intentionally so. It ensures the presenter always works with the active UI.

Any "repetition" is generally very lightweight unless you’re doing expensive work inside takeView() — which you should avoid.

Best Practice: Use this pattern:

@Override protected void onResume() { super.onResume(); mPresenter.takeView(this); }

@Override protected void onPause() { mPresenter.dropView(); super.onPause(); } This ensures a clean attach/detach cycle with the view — helping with testability, memory safety, and avoiding UI crashes when the view is gone.

Just don’t do heavy work in takeView() If you're loading data or triggering expensive processes in takeView(), you might want to move that logic into a separate method, like start() or loadData(), and only call it if needed.

VaradGupta23 avatar Aug 06 '25 04:08 VaradGupta23