How to fetch main object and sub objects with WebFlux

Viewed 53

I'm building a Content Management System with Pages that contain Blocks. I fetch a page with an id and then fetch blocks that is associated with the same page id. In a blocking fashion, I would do:

Page page = repo.getPageById(47);
page.setBlocks(repo.getBlocksByPageId(47));

When doing this reactive it is a mess of flatMaps and zipWith:

Mono<Page> = repo.getPageById(47)
    .flatMap(page -> repo.getBlocksByPageId(47).collectList().zipWith(Mono.just(page)))
    .flatMap(t -> {
      List<Block> blocks = t.getT1();
      Page page = t.getT2();
      page.setBlocks(blocks);
      return Mono.just(page);
    });

Can you recommend better ways of accomplishing the same result?

1 Answers

You could zip the 2 Monos from the start and use map instead of flatMap.

Mono<Page> result = repo.getPageById(47)
           .zipWith(repo.getBlocksByPageId(47).collectList())
           .map(t -> {
               Page page = t.getT1();
               page.setBlocks(t.getT2());
               return page;
           });
Related