Skip to content

Instantly share code, notes, and snippets.

@PaNaVTEC PaNaVTEC/Coordinator.java
Last active Nov 4, 2016

Embed
What would you like to do?
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
You can’t perform that action at this time.