Last active
May 27, 2020 14:15
-
-
Save sebersole/142765fe2417492061e92726e7cb6bd8 to your computer and use it in GitHub Desktop.
LoadEventListener - continuation approach
This file contains hidden or 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
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 ); | |
} | |
} | |
} |
This file contains hidden or 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
/** | |
* 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