Skip to content

Instantly share code, notes, and snippets.

@dimitarg
Created November 25, 2016 15:43
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 dimitarg/0d14f4b28719a8e5138198de9a551656 to your computer and use it in GitHub Desktop.
Save dimitarg/0d14f4b28719a8e5138198de9a551656 to your computer and use it in GitHub Desktop.
package com.dimitarg.demo;
import io.netty.util.concurrent.EventExecutor;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.Promise;
import java.util.function.Function;
/**
* Created by fmap on 25.11.16.
*/
public class FutureOps
{
private static final Exception CANCEL = new Exception()
{
@Override public synchronized Throwable fillInStackTrace()
{
return this;
}
};
private final EventExecutor ex;
public FutureOps(EventExecutor ex)
{
this.ex = ex;
}
public <A, B> Future<B> map(Future<A> future, Function<A, B> f)
{
Promise<B> result = ex.newPromise();
failOrEffect(future, result, () -> result.setSuccess(f.apply(future.getNow())));
return result;
}
public <A, B> Future<B> bind(Future<A> future, Function<A, Future<B>> f)
{
Promise<B> result = ex.newPromise();
failOrEffect(future, result, () -> {
Future<B> next = f.apply(future.getNow());
failOrEffect(next, result, () -> result.setSuccess(next.getNow()));
});
return result;
}
public <A> Future<A> unit(A a)
{
Promise<A> result = ex.newPromise();
result.setSuccess(a);
return result;
}
public static void failOrEffect(Future<?> upstream, Promise<?> promise, Effect f)
{
upstream.addListener(x ->
{
if (upstream.isCancelled())
{
promise.setFailure(CANCEL);
}
else if (upstream.cause() != null)
{
promise.setFailure(x.cause());
}
else
{
f.run();
}
});
}
public interface Effect
{
void run();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment