1

How can I return an object or list after using Blocking.get() method in Ratpack?

Blocking.get(()->
            xRepository.findAvailable()).then(x->x.stream().findFirst().get());

Above line returns void - I want to be able to do something like below so that it returns the object in the then clause. I tried adding a return statement but doesn't work.

Object x = Blocking.get(()->
            xRepository.findAvailable()).then(x->x.stream().findFirst().get());
Szymon Stepniak
  • 40,216
  • 10
  • 104
  • 131
somename
  • 978
  • 11
  • 30

1 Answers1

1

You can use map to work with the value when it's available.

Blocking.get(() -> xRepository.findAvailable())
         .map(x -> x.stream().findFirst().get())
         .then(firstAvailable -> ctx.render("Here is the first available x " + firstAvailable))

Ratpack's Promise<T> does not provide blocking operation like Promise.get() that blocks current thread and returns a result. Instead you have to subscribe to the promise object. One of the methods you can use is Promise.then(Action<? super T> then) which allows you to specify and action that will be triggered when given value is available. In above example we use ctx.render() as an action triggered when value from blocking operation is ready, but you can do other things as well.

Szymon Stepniak
  • 40,216
  • 10
  • 104
  • 131
Dan Hyun
  • 536
  • 3
  • 7