Home > front end >  Mono<List<Object>> to List<Object> in Java
Mono<List<Object>> to List<Object> in Java

Time:11-01

I am not able to process Mono<List> to List but I can't seem to do it. I have read somewhere that "flatmap" can be used but I am not able to do it as well. I don't want to use ".block()" method for this scenario.

A code example could be:

PagePublisher<Address> someAddressPage = 
       someService.getPagePublisherForAddress();
Mono<List<Address>> addressListMono = 
       Flux.from(someAddressPage.items()).collectList();

I need to get List<Address> from Mono<List<Address>>. The method return type is List<Address>.

I am not sure how to go about that and I am relatively new to reactive. Need help in that regard.

Thank you

CodePudding user response:

Using block() is actually the only way to get the object from a Mono when it is emitted. However, you should avoid it at all costs because it defeats the purpose of using the reactive stack given that it actually blocks the thread waiting for the object to be emitted from the Mono.

This means that while working with reactive programming you should actually work with Mono and Flux so that your application is really reactive. The consequence of this is that you must change the return type of your method to return Mono<List<Address>> instead.

CodePudding user response:

Its impossible to get List<Address> from Mono<List<Address>>. If the List isn't available yet since Mono and Flux are asynchronous/non-blocking by their nature, you can't get it except by waiting until it comes in and that's what blocking is.

Ideally, your method should return Mono<List<Address>> or just Flux<Address> and the caller of this method should subscribe to the results. Since you are using Spring Webflux, complete chain should be reactive.

You can subscribe to the Mono from the calling method and the Subscriber you pass will get the List when it becomes available. E.g.

addressListMono.subscribe(
  addressList -> doSomething(addressList), 
  error -> error.printStackTrace(), 
  () -> Console.out.println("completed without a value")
)
  • Related