简体   繁体   English

Java Stream 具有反应性谓词的过滤器

[英]Java Stream Filter with a reactive predicate

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"如果我在 asyncOperation 执行后调用“.block()”,我会收到错误“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?实现它的更好方法是什么?

You can supply async predicate to filterWhen :您可以向filterWhen提供异步谓词:

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

Signature:签名:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM