Stream> 转换为 Flux 在 Spring Reactor 中

huangapple go评论96阅读模式
英文:

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

问题

让我们假设我有一个名为 ProductSupplier 的类,它允许通过产品 ID 获取产品。但是它有一些限制,每次请求只能加载一个产品。

  1. public interface ProductSupplier {
  2. public Mono<Product> getById(Long productId);
  3. }

现在我正在编写 ProductService,在其中我需要通过 ID 获取产品列表。

  1. public interface ProductService {
  2. ProductSupplier supplier;
  3. public Mono<List<Product>> getByIds(Collection<Long> ids) {
  4. return Flux.fromIterable(ids)
  5. .flatMap(supplier::getById) // 得到 Flux<Product>
  6. .collectList();
  7. }
  8. }
英文:

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.

  1. public interface ProductSupplier {
  2. public Mono&lt;Product&gt; getById(Long productId);
  3. }

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

  1. public interface ProductService {
  2. ProductSupplier supplier;
  3. public Mono&lt;List&lt;Product&gt;&gt; getByIds(Collection&lt;Long&gt; ids) {
  4. return ids.stream()
  5. .map(supplier::getById)//Stream&lt;Mono&lt;Product&gt;&gt;
  6. //how to get Flux&lt;Product&gt; here?
  7. .collectList();
  8. }
  9. }

答案1

得分: 1

你可以直接在流(flux)上进行操作,而不是在流(stream)上操作:

  1. Flux<Product> flux = Flux
  2. .fromIterable(ids)
  3. .flatMap(supplier::getById);
英文:

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

  1. Flux&lt;Product&gt; flux = Flux
  2. .fromIterable(ids)
  3. .flatMap(supplier::getById);

huangapple
  • 本文由 发表于 2020年9月11日 23:29:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/63850056.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定