Stream<Mono<T>> to Flux<T> in spring reactor

1.2k views Asked by At

Lets say I have ProductSupplier which allow to get product by id. But it has restrictions and per one request you can load only one product.

public interface ProductSupplier {
    public Mono<Product> getById(Long productId);
}

Now I'm writing ProductService in which I need to fetch a list of products by id

public interface ProductService {
    ProductSupplier supplier;

    public Mono<List<Product>> getByIds(Collection<Long> ids) {
        return ids.stream()
                  .map(supplier::getById)//Stream<Mono<Product>>
                  //how to get Flux<Product> here?
                  .collectList();
    }
}
1

There are 1 answers

0
sp00m On

You could work on a flux directly instead of a stream:

Flux<Product> flux = Flux
  .fromIterable(ids)
  .flatMap(supplier::getById);