moxy-community / Moxy

Moxy is MVP library for Android with incremental annotation processor and ktx features
MIT License
327 stars 33 forks source link

When using getViewState in a for loop, the view method only works once #104

Closed noname-developer closed 4 years ago

noname-developer commented 4 years ago

Here is an example code where I call the view method through a presenter in a loop:

Presenter:

  for (int i = 0; i<exampleList.size(); i++) {
        String title = exampleList.get(i).getTitle;
        int id = exampleList.get(i).getID;
        getViewState().addMenuItem(title, id);
        Log.d(TAG, "addMenuItem: "+i);
            }

Activity:

@Override
    public void addMenuItem(String title, int id) {
        navMenuCategory.add(R.id.menu_category, id, Menu.FIRST, title);
    }

For example: I need to add 5 menu items. Of these, only the last fifth item will be added. Default Strategy (Tried to add SingleStrategy, AddToEndSingleStrategy, did not help).

Is there a solution to this problem, or is it better for me to transfer the list of necessary items in view and cyclically add them to the menu?

Thank you in advance for your response!

alaershov commented 4 years ago

The best solution is to have a method with a list parameter and AddToEndSingleStrategy: void showMenuItems(List<MyMenuItem> items); It's a better abstraction and works fine with Moxy. A loop in presenter is not a good idea, because it makes Presenter more complicated and forces you to have an additional method in View, like clearMenuItems(). Also it's hard to make this work correctly ViewState strategies, as you've already found out.

noname-developer commented 4 years ago

Thanks for your reply! I will use your recommendation. I also wanted to clarify about the cycles, it turns out they are better to use in the view and interactors, bypassing the presenter?

alaershov commented 4 years ago

Not sure what you mean, feel free to use cycles anywhere you want) It's just in this particular case using the loop to populate View's menu seems like a bad separation of concerns and doesn't play nice with Moxy.

noname-developer commented 4 years ago

I understood. Thanks again!