Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@sebersole
Last active May 27, 2020 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sebersole/142765fe2417492061e92726e7cb6bd8 to your computer and use it in GitHub Desktop.
Save sebersole/142765fe2417492061e92726e7cb6bd8 to your computer and use it in GitHub Desktop.
LoadEventListener - continuation approach
LoadEventHandler handler = ...;
EventListenerGroup<LoadEventListener> listenerGroup = ...;
listenerGroup.withListeners(
(listeners) -> {
if ( listeners == null ) {
// short-circuit
return handler.load( ... );
}
else if ( listeners.length == 1 ) {
final LoadEvent event = new LoadEvent( ... );
listeners[0].onLoad(
event,
() -> {
final Object result = handler.load( ... );
event.setResult( result );
}
);
return event.getResult();
}
else {
return LoadEventListenerStack.process( ..., listeners, handler );
}
}
);
class LoadEventListenerStack implements LoadEventListenerContinuation {
public static Object process(..., LoadEventListener[] listeners, LoadEventHandler handler) {
return new LoadEventListenerStack( ..., listeners, handler ).process();
}
private final LoadEvent event;
private final MutableInteger currentPosition = new MutableInteger( 1 );
private LoadEventListenerStack(..., LoadEventListener[] listeners, LoadEventHandler handler) {
event = new LoadEvent( ... );
...
}
private Object process() {
listeners[0].onLoad( event, this );
return event.getResult();
}
@Override
void continue() {
final int position = currentPosition.getAndIncrement();
if ( position >= listeners.length ) {
// we reached the end of the listeners - trigger the handler
final Object result = handler.load( ... );
event.setResult( result );
}
else {
listeners[ position ].onLoad( event, this );
}
}
}
/**
* Load-related event listener providing
*/
public interface LoadEventListener extends Serializable {
void onLoad(LoadEvent event, LoadEventListenerContinuation continuation);
}
@FunctionalInterface
public interface LoadEventListenerContinuation {
void continue();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment