Monique890
Monique890

Reputation: 93

Android having a single presenter with 3 fragments

This is more of a conceptual question of MVP in Android. I have 3 fragments and I am trying to use 1 presenter for all 3 of them.

I am more skeptical of these things -

a) Creating new instance of presenter in onCreate() of fragment which I do like this -

presenter = new MyPresenter();
presenter.setView(this);

So 3 fragments opened will create 3 instances of presenter. Is it a good idea?

b) The view of 1 fragment must be overriden in 2nd and 3rd fragment although they are not used and they are just empty methods making my code length of 2nd and 3rd fragments long. IS this a good idea?

c) Although I do in onDestory() of fragment presenter.onDestroy(), the presenter will do super.onDestory(). The BasePresenter which I have will destroy the views something like this -

public void onDestroy() {
    this.view = null;
}

Though the view is destroyed, is the presenetr garbage collected? Because next fragment will create new instance of presenter and I dont want several instances running.

Upvotes: 3

Views: 387

Answers (1)

Truong Giang Dam
Truong Giang Dam

Reputation: 500

So 3 fragments opened will create 3 instances of presenter. Is it a good idea?

You should do that, each presenter instance for each fragment. But I suggest you create specific presenter for specific fragment. It's clear, easy to improvement and maintain.

The view of 1 fragment must be overriden in 2nd and 3rd fragment although they are not used and they are just empty methods making my code length of 2nd and 3rd fragments long. IS this a good idea?

Of course No, that's the bad code.

Though the view is destroyed, is the presenetr garbage collected? Because next fragment will create new instance of presenter and I dont want several instances running.

It will be clean by GC. You created new presenter instance every onCreate() call so there are three instance here. It will be clean because it only associate with specific one fragment.

Hope it help !

Upvotes: 2

Related Questions