Reactive programming with Java 8 and simple-react : firstOf, allOf & anyOf
firstOf!
1 min readMar 25, 2015
simple-react can take an array of FutureStreams and ‘run a race’ between them. It will return a Stream of values from the first one to start emitting values, the other Streams will be closed.
Example
LazyFutureStream stream1 =
LazyFutureStream.sequentialBuilder()
.react(()->loadFromDb())
.map(this::convertToStandardFormat)LazyFutureStream stream2 =
LazyFutureStream.sequentialBuilder()
.react(()->loadFromService1())
.map(this::convertToStandardFormat)LazyFutureStream stream3 =
LazyFutureStream.sequentialBuilder()
.react(()->loadFromService2())
.map(this::convertToStandardFormat)LazyFutureStream.firstOf(stream1,stream2,stream3)
.map(this::save)
.runOnCurrent()
anyOf!
anyOf continues the Stream with the first value in a Stream to be emitted.
LazyFutureStream.parallelBuilder()
.react(() -> loadFromDb(),
() -> loadFromService1(),
() -> loadFromService2())
.anyOf(Function.<String>identity())
.map(this::convertToStandardFormat)
.peek(System.out::println)
.map(this::saveData)
.run(()-> new ArrayList<>());
NB filtering short-circuits the internal chain of CompletableFutures, and may result in an empty completed value.
allOf!
allOf asynchronously collects all the data in a Stream into a Collection. It’s roughly equivalent to collect or block, but is asynchronous and the Stream can continue, albeit with a single value.