Java Stream Filter with a reactive predicate

Viewed 361

I need to filter a collection using a reactive predicate.

Something like this (obviously the real code is not so simple):

private void filterElements(List<Element> elements) {
    // Flux.fromStream(elements.stream()) // maybe I have to make this?
    elements.stream()
    .filter(this::asyncOperation)
    .collect(Collectors.toList());
}

private Mono<Boolean> asyncOperation(Element e) {
    // External service invocation that return a Mono<Boolean>
    Mono.just(Boolean.TRUE); // this is only an example
}

If I call ".block()" after asyncOperation execution, I get the error "java.lang.IllegalStateException: block()/blockFirst()/blockLast() are blocking, which is not supported in thread parallel-1"

Is it possible? Which is the better way to achieve it?

1 Answers

You can supply async predicate to filterWhen:

Flux...filterWhen(t -> this.asyncOp(t))

Signature:

Flux<T> filterWhen(Function<? super T, ? extends Publisher<Boolean>> pred)
Related