restoring state in a presenter with MVP


restoring state in a presenter with MVP



https://medium.com/@cervonefrancesco/model-view-presenter-android-guidelines-94970b430ddf says to restore state in the model instead of the presenter. What if I have a very simple "model", say a binary toggle that updates a textview to be on or off? Creating a model Toggle class that has a single string value seems like overkill.



Another option is to pass the bundle from my Activity into a corresponding method in my presenter inside onSaveInstanceState and restore it similarly with onCreate. But the article also says that we should avoid having android dependencies in the presenter.



Finally I tried using Icepick but this did not work:



MainActivity.java


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Icepick.restoreInstanceState(this, savedInstanceState);
(Button) findViewById(R.id.btn).setOnClickListener(this);
presenter.onCreate();
}

@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Icepick.saveInstanceState(this, outState);
}

@Override
public void onClick(View view) {
presenter.onButtonClicked();
}

@Override
public void updateState(String state) {
tv.setText(state);
}



MainPresenter.java


public class MainPresenter {

private MainView mainView;
@State String toggle;

@Inject
public MainPresenter(MainView mainView) {
this.mainView = mainView;
}

void onCreate() {
mainView.updateState(toggle);
}

void onButtonClicked() {
mainView.updateState(toggle.equals("on") ? "off" : "on");
}
}



What are my options? If I have to use the model approach can I see an example of this for my case?




1 Answer
1



If you're using annotation processing to maintain the state, it won't automatically populate data into your presenter without Icepick.saveInstanceState(this, outState) which you can't call in the presenter.


Icepick.saveInstanceState(this, outState)



@State String toggle;


@State String toggle;



This line should be present in the activity. Have a method in your presenter to request data by toggle. Something like this:


@State String toggle = "off"; //default value

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Icepick.restoreInstanceState(this, savedInstanceState);
(Button) findViewById(R.id.btn).setOnClickListener(this);
presenter.onCreate();
presenter.setState(toggle)
}



You can store this value as the global variable in the presenter and decide the app flow accordingly.






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

How to input without newline? (Python)

C++ thread error: no type named ‘type’ MINGW

Analog for TagView in flutter