Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Mono<List<T>> to Stream<T>?

I have a code that uses WebClient to create a Mono<List<T>> from a Json array result. The bodyToMono method returns a Mono<List<T> object, which I subscribe to and then get a parallelStream

    final WebClient client = WebClient.create(daemonEndpoint);
    client.get()
        .uri("/services?label=com.docker.stack.namespace")
        .accept(MediaType.APPLICATION_JSON)
        .retrieve()
        .bodyToMono(new ParameterizedTypeReference<List<Map<String, Object>>>() {
        })
        .subscribe(services -> services.parallelStream()
            .map(e -> {
                final String id = (String) e.get("ID");

What I want to know is whether there is a solution that removes that subscribe part.

like image 623
Archimedes Trajano Avatar asked Jan 25 '26 03:01

Archimedes Trajano


1 Answers

From my experience with reactor you can't transform your Mono to Stream without blocking call, it can be done as follow:

Stream<T> stream = yourMono<T>.map(it -> it.parallelStream()).block()

Another way just process it in reactive approach (note, anyway someone have to subscribe to your publisher, it can't be done by itself):

yourMono<T>.flatMapMany(Flux::fromIterable)
           .flatMap(it -> {
              //there goes your <Map<String, Object>>
           });
like image 96
Vladlen Gladis Avatar answered Jan 26 '26 17:01

Vladlen Gladis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!