Last active
November 4, 2016 22:49
-
-
Save PaNaVTEC/674e1007a0ed24c8d8f9 to your computer and use it in GitHub Desktop.
Coordinates various actions and fires a callback when all are complete
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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