0

I have a search engine with books. Each book has a binding/format. I want to present which other bindings/formats each book is available in. This is done in a separate query.

Procedurally like so:

List<Book> books = bookRepo.search("title:'Steve the dog'");
for(Book book:books) {
   String subquery="title:'%s' AND author:'%s' AND NOT binding:'%s'".formatted(
       book.title(), book.author(), book.binding()
   );
   List<Book> related = bookRepo.search(subquery);
   book.setRelated(related);
}

Now I have made the repository somewhat reactive and bookRepo.search() now returns a Mono<List>.

How can I lookup related bindings for each element in list when doing it reactive?

Edit:

This is what I have come up with based on suggestions below.

public class BookService {
  BookRepo bookRepo;

  Mono<List<Book>> searchBooks(String query) {
    return bookRepo.search(query)
        .flatMap(bookList -> Flux.fromIterable(bookList)
            .flatMap(book -> Mono.just(book)
                .zipWith(bookRepo.findRelatedBindings(book))
                .flatMap(t -> Mono.just(t.getT1().withRelatedBindings(t.getT2()))))
            .collectList());

  }
}

interface BookRepo {
  Mono<List<Book>> search(String query);

  Mono<List<BindingRelation>> findRelatedBindings(Book book);
}

interface Book {
  Book withRelatedBindings(List<BindingRelation> bindings);
}

Is there a neater, better way of doing this convoluted mess of flatmaps and zipWiths?

Fredrik Rambris
  • 316
  • 3
  • 10
  • `Mono` API is part of the Project Reactor library. If you wonder which operator fits your case, I would suggest you go through the `Which operator do I need?` section of the official reference guide. – lkatiforis Jan 13 '22 at 08:53
  • please also look at this stackoverflow question : https://stackoverflow.com/questions/70639975/how-to-zip-nested-lists-with-reactor-and-r2dbc/70647332#70647332 . – Harry Jan 13 '22 at 09:37

0 Answers0