[2.0] Immediate promises

113 views
Skip to first unread message

James Roper

unread,
Apr 23, 2012, 6:14:38 AM4/23/12
to play-fr...@googlegroups.com
I have an interface, written in Java, that has an implementation that makes webservice calls.  Everything it returns is promises for objects.  In some environments, I want to mock this interface, so that, for example, when running CI, my service isn't dependent on a third party server.  In my mock, there's no call to anything that returns a promise, the results are available immediately.  So I want to construct a promise that just has the value immediately available.  Does play provide anything that will do this?  I tried a naive approach of providing my own promise implementation in Java:

    public class Immediate<T> extends F.Promise<T> {
        private final T value;
        Immediate(T value) {
            super(null);
            this.value = value;
        }

        @Override
        public T get() {
            return value;
        }

        @Override
        public void onRedeem(F.Callback<T> callback) {
            try {
                callback.invoke(value);
            } catch (Throwable t) {
                throw new RuntimeException(t);
            }
        }

        @Override
        public <B> F.Promise<B> map(F.Function<T, B> function) {
            try {
                return new Immediate<B>(function.apply(value));
            } catch (Throwable t) {
                throw new RuntimeException(t);
            }
        }

        @Override
        public <B> F.Promise<B> flatMap(F.Function<T, F.Promise<B>> function) {
            try {
                return function.apply(value);
            } catch (Throwable t) {
                throw new RuntimeException(t);
            }
        }

        @Override
        public Promise<T> getWrappedPromise() {
            return null;
        }
    }

But this doesn't work when returning it as an AsyncResult back to play framework, because play framework expects a wrapped Scala promise.  Does play framework provide any Scala promise classes that have a value immediately available?  If not, it should, and it should provide something similar for Java, so that interfaces can be designed to use Promises, but not require that the underlying implementation is asynchronous.

Julien Richard-Foy

unread,
Apr 23, 2012, 6:20:47 AM4/23/12
to play-fr...@googlegroups.com
I think we miss a constructor for your case. Can you file a ticket?
In the meantime you should be able to workaround with the following:

new F.Promise(Promise.pure(42))

James Roper

unread,
Apr 23, 2012, 8:16:20 AM4/23/12
to play-fr...@googlegroups.com
Thanks.  In Java, it's actually new F.Promise(Promise$.MODULE$.pure(42)).  I've added a constructor that does this for you and filed a pull request:

https://github.com/playframework/Play20/pull/243
Reply all
Reply to author
Forward
0 new messages