Skip to content

View commands state strategy

Yuri Shmakov edited this page Apr 6, 2017 · 8 revisions


When you apply annotation @InjectViewState to some Presenter, Moxy compiler generate ViewState-class for View, by which is typed this Presenter. This ViewState-class contains nested Command-classes for each command that View can executes. And by default when you send some command to View via ViewState, this command stack to command's queue as is. And each time when some View attaches to Presenter/ViewState, it applies this queue. Thus View become to right state.

But sometimes we want to manage this command's queue. Moxy provides @StateStrategy annotation and StateStrategy interface for this. By this way you can manage how to changes command's queue when some command start execute and finish. You can also apply this strategy to the View interface. Then this strategy apply to each View's commands by default.

How does it works

It starts from moment when you send command to ViewState. Firstly executed method StateStrategy.beforeApply(currentState, incomingCommand). There you can save incomingCommand to command's queue. Or clear queue. Or something else, what you need. After this, command applies to Views which attached to Presenter/ViewState. There are two cases:

  1. If this ViewState have attached Views. Then command applies to these and then executes StateStrategy.afterApply(currentState, incomingCommand). There you can remove incomingCommand, for example. Or do nothing.
  2. If this ViewState haven't attached Views. Then nothing will be happen. In the future, when some View will be attached to Presenter/ViewState, each command's queue will be applied to this View. And then will be executed StateStrategy.afterApply(currentState, incomingCommand) too.

Existing strategies

Currently Moxy contains few strategies. But you can create your own if you want. Just implements StateStrategy interface. But in most cases existing strategies are comprehensive. These are they:

AddToEndStrategy (used by default):

Command will be added to end of commands queue.

AddToEndSingleStrategy (most popular):

Command will be added to end of commands queue. If commands queue contains same type command, then existing command will be removed.

SingleStateStrategy :

This strategy will clear current commands queue and then incoming command will be put in.

OneExecutionStateStrategy :

Command will be saved in commands queue. And this command will be removed after first execution.

SkipStrategy :

Command will not be put in commands queue.

Usages example

You can find some examples in github-sample, like this.

Custom strategies

Library couldn't contains all strategies which we can imagine. But you can make your own strategy. There are few examples of custom strategies:


Command will be added to end of commands queue. If commands queue contains commands with same tag, then existing commands will be removed.

You can’t perform that action at this time.