Skip to content

Instantly share code, notes, and snippets.

@PaNaVTEC
Last active November 4, 2016 22:49
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PaNaVTEC/674e1007a0ed24c8d8f9 to your computer and use it in GitHub Desktop.
Save PaNaVTEC/674e1007a0ed24c8d8f9 to your computer and use it in GitHub Desktop.
Coordinates various actions and fires a callback when all are complete
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class Coordinator {
private List<String> actions;
private Set<String> completedActions = new TreeSet<>();
private CoordinatorCompleteAction coordinatorCompleteAction;
public Coordinator(CoordinatorCompleteAction coordinatorCompleteAction, String... actions) {
if (coordinatorCompleteAction == null) {
throw new NullPointerException("Coordinate complete action must not be null");
}
if (actions == null || actions.length == 0) {
throw new IllegalArgumentException("No actions configured");
}
this.coordinatorCompleteAction = coordinatorCompleteAction;
this.actions = Arrays.asList(actions);
}
public void completeAction(String action) {
if (actions.contains(action)) {
completedActions.add(action);
checkComplete();
}
}
public void reset() {
completedActions.clear();
}
private void checkComplete() {
if (actions.size() == completedActions.size()) {
coordinatorCompleteAction.onCoordinatorComplete();
}
}
public static interface CoordinatorCompleteAction {
public void onCoordinatorComplete();
}
}
public class CoordinatorSample {
private static final String ACTION_1 = "ACTION_1";
private static final String ACTION_2 = "ACTION_2";
Coordinator coordinator = new Coordinator(new CoordinatorCompleteAction() {
launchMyAwesomeAction();
}, ACTION_1, ACTION_2);
public void sampleMethod() {
doSomeAsyncWork.callback(onComplete() {
coordinator.completeAction(ACTION_1);
}
doSomeAsyncWork.callback(onComplete() {
coordinator.completeAction(ACTION_2);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment