delight.async.flow.CallbackMap Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of delight-async Show documentation
Show all versions of delight-async Show documentation
Asynchronous utilities for Java and GWT applications. Includes a simple promise implementation for Java.
/*******************************************************************************
* Copyright 2011 Max Erik Rohde http://www.mxro.de
*
* All rights reserved.
******************************************************************************/
package delight.async.flow;
import delight.async.Value;
import delight.async.callbacks.ListCallback;
import delight.async.callbacks.ValueCallback;
import delight.functional.collections.CollectionsUtils;
import delight.functional.collections.IdentityArrayList;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* This utility class supports in writing Java in a more asynchronous style.
* This class allows to collect the results from various callbacks, which
* result from calling a method on all elements of a list. The callback provided
* by this class will only be called if all the callbacks for the individual
* list elements have been executed.
*
* @author Max Rohde
*
* @param
* @param
*/
public class CallbackMap {
final Map responseMap;
final List messages;
final int expectedSize;
final ListCallback callback;
public ValueCallback createCallback(final GInput message) {
return new ValueCallback() {
@Override
public void onSuccess(final GOutput response) {
synchronized (responseMap) {
responseMap.put(messages.indexOf(message), response);
if (CollectionsUtils.isMapComplete(responseMap, expectedSize)) {
final List localResponses = CollectionsUtils
.toOrderedList(responseMap);
callback.onSuccess(localResponses);
}
}
}
Value failureReported = new Value(false);
@Override
public void onFailure(final Throwable t) {
// failure should be reported only once.
synchronized (failureReported) {
if (!failureReported.get()) {
callback.onFailure(t);
} else {
throw new RuntimeException(t); // TODO maybe disable ...
}
failureReported.set(true);
}
}
};
}
public CallbackMap(final List messages,
final ListCallback callback) {
super();
this.messages = new IdentityArrayList(messages);
this.responseMap = new HashMap();
expectedSize = messages.size();
this.callback = callback;
if (expectedSize == 0) {
this.callback.onSuccess(new ArrayList(0));
}
}
}