public class MultiReady {
public MultiReady(Ready target, Object... states) {
}
public MultiReady(ReadyCallback target, Object... states) {
}
public void setReady(Object state) {
}
}
The MultiReady class is used to coordinate multiple asynchronous states to trigger a ready callback. The constructor takes a list of state objects and a target (either a Ready or ReadyCallback object, both defined on the preceding Ready Processing page). The target is triggered when all states have been marked ready.
In effect, the MultiReady class lets you code things like: "When state (or step) A and state B and state C are all finished, then please let me know."
This article discusses the MultiReady class.
The following defines the MultiReady class:
MultiReady
classpublic class MultiReady {
public MultiReady(Ready target, Object... states) {
}
public MultiReady(ReadyCallback target, Object... states) {
}
public void setReady(Object state) {
}
}
There are two constructors: one that takes a Ready object, and one that takes a ReadyCallback object.
When one of the state’s becomes ready, the code calls the setReady()
method.
At this point in time, it checks to see if all states are finished. If so, then either the setReady()
or the onReady()
method is called (based on which constructor was used to create this object).
The following example shows a MyService class that needs to perform some processing, but must wait until an external object calls both its init()
and connect()
methods.
To achieve this, MyService creates a MultiReady object that contains two states: STATE_INIT
and STATE_CONNECT
. When both of those states are finished, then the onReady()
method of the ReadyCallback interface is called.
As you can see, this is a very easy way to ensure that multiple states are finished before preceding on with some other task.
The state objects can be of any type.
MyService
classpublic class MyService implements ReadyCallback {
private static final String STATE_INIT = "A";
private static final int STATE_CONNECT = 2;
private final MultiReady multiReady;
private boolean everythingIsReady;
public MyService() {
multiReady = new MultiReady(this, STATE_INIT, STATE_CONNECT);
}
public void init() {
// Execute code, then indicate state 1 is ready:
multiReady.setReady(STATE_INIT);
}
public void connect() {
// Execute code, then indicate state 2 is ready:
multiReady.setReady(STATE_CONNECT);
}
// Implement the ReadyCallback interface.
@Override
public void onReady() {
// Called when both the init() and connect() methods have finished:
everythingIsReady = true;
}
}
Here’s the unit test that verifies the above code works as desired:
class UT_MyService {
@Test
void verify_all() {
MyService myService = new MyService();
assertThat(myService.everythingIsReady, equalTo(false));
myService.init();
assertThat(myService.everythingIsReady, equalTo(false));
myService.connect();
assertThat(myService.everythingIsReady, equalTo(true));
}
}