英文:
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<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
得分: 1
你可以直接在流(flux)上进行操作,而不是在流(stream)上操作:
Flux<Product> flux = Flux
.fromIterable(ids)
.flatMap(supplier::getById);
英文:
You could work on a flux directly instead of a stream:
Flux<Product> flux = Flux
.fromIterable(ids)
.flatMap(supplier::getById);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论