Stream> 转换为 Flux 在 Spring Reactor 中

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

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

问题

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

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

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

public interface ProductService {
    ProductSupplier supplier;

    public Mono<List<Product>> getByIds(Collection<Long> ids) {
        return Flux.fromIterable(ids)
                   .flatMap(supplier::getById) // 得到 Flux<Product>
                   .collectList();
    }
}
英文:

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&lt;Product&gt; 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&lt;List&lt;Product&gt;&gt; getByIds(Collection&lt;Long&gt; ids) {
        return ids.stream()
                  .map(supplier::getById)//Stream&lt;Mono&lt;Product&gt;&gt;
                  //how to get Flux&lt;Product&gt; here?
                  .collectList();
    }
}

答案1

得分: 1

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

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

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

Flux&lt;Product&gt; flux = Flux
  .fromIterable(ids)
  .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:

确定