首页 > 解决方案 > 如何调用返回 Observable 的多个 API并将他们的响应汇总到单个对象

问题描述

我必须创建一个名为 say Product.java的聚合 POJO ,通过调用多个源/Rest API(#sources 可以是任何数字)并解析它们的各个响应(Observable<Response>)以填充 Product.java 中的相关字段

Observable.zip() 有点适合我的要求,但它需要一个固定的编号。args,而在我的情况下,#sources (args) 可以是任何可配置的数字。

有没有通用/更清洁的方法来做到这一点?

List<Source> sources = //Some configuration, where sources.size() 
// Call all source REST APIs in parallel where each returns an Observable<Response>
// Parse each Observable<Response> & populate the relevant fields in a shared Product.java Object. (No two responses will try to populate the same field in Product)

标签: javajava-8rx-javareactive-programmingrx-java2

解决方案


如果顺序不重要,只需 .merge() 和 .scan(); 如果它很重要,请使用 .concat() 而不是 .merge()

final Observable<MyContainer> myContainer = Observable
  .merge(sources)
  .scan(new MyContainer(), (myContainer, newProduct) -> {
     // add newProduct to myContainer
     return myContainer;
  })

推荐阅读