【问题标题】:RxJava2 combine multiple observables to make them return single resultRxJava2 组合多个 observable 以使它们返回单个结果
【发布时间】:2018-10-09 20:11:15
【问题描述】:

如何将 observables 发出的多个结果组合成一个结果并发出一次?

我有改造服务:

public interface MyService {

    @GET("url")
    Observable<UserPostsResult> getUserPosts(@Query("userId") int id);

    @GET("url")
    Observable<UserPostsResult> getUserPosts(@Query("userId") int id, @Query("page") int pageId);
}

我有一个模型:

public class UserPostsResult {

   @SerializedName("posts")
   List<UserPost> mPosts;

   @SerializedName("nextPage")
   int mPageId;
}

我还有 ids List&lt;Integer&gt; friendsIds;

我的目标是有一个像这样的方法:

public Observable<Feed> /*or Single<Feed>*/ getFeed(List<Integer> ids) {
    ...
}

它返回一个 ObservableSingle,它执行以下操作:

  • 将所有getUserPosts(idFromList) 合并为一个可观察对象
  • 对于每个UserPostsResult必须做的:

    if (userPostResult.mPageId > -1) getUserPosts(currentUserId, userPostResult.mPageId);

    并将这个结果合并到之前的userPostResult

  • 返回一个模型作为所有操作的结果。

结果类:

public class Feed {
    List<UserPost> mAllPostsForEachUser;
}

编辑(更多细节):

我的客户规范是我必须从社交网络用户帖子中获取,无需登录,无需令牌请求。所以我必须解析 HTML 页面。这就是为什么我有这个复杂的结构。

编辑(部分解决方案)

public Single<List<Post>> getFeed(List<User> users) {
    return Observable.fromIterable(users)
            .flatMap(user-> mService.getUserPosts(user.getId())
                    .flatMap(Observable::fromIterable))
            .toList()
            .doOnSuccess(list -> Collections.sort(list, (o1, o2) ->
                    Long.compare(o1.getTimestamp(), o2.getTimestamp())
            ));
}

此解决方案不包括页面问题。这就是为什么它只是部分解决方案

【问题讨论】:

    标签: java android retrofit rx-java2


    【解决方案1】:

    有许多运算符可以将事物转换为其他事物。 fromIterable() 将发出 iterable 中的每个项目,flatMap() 会将一种类型的 observable 转换为另一种类型的 observable 并发出这些结果。

    Observable.fromIterable( friendsIds )
      .flatMap( id -> getUserPosts( id ) )
      .flatMap( userPostResult -> userPostResult.mPageId 
                ? getUserPosts(currentUserId, userPostResult.mPageId)
                : Observable.empty() )
      .toList()
      .subscribe( posts -> mAllPostsForEachUser = posts);
    

    【讨论】:

    • 以后如何将所有结果合并到一个模型中?
    • 我编辑了帖子以展示如何将帖子收集到列表中,然后分配给成员。
    • toList() 这里返回 Single>> 而不是 Single>
    • 我找到了部分解决方案。在问题底部查看我的最新编辑。
    • 如果您(或其他人)能找到页面问题的解决方案,我会将其标记为已接受。但是您当前的答案并不能解决问题
    【解决方案2】:

    如果您需要将两个响应合二为一,您应该使用 Single.zip

    Single.zip(firsSingle.execute(inputParams), secondSingle.execute(inputPrams),
                BiFunction<FirstResponse, SecondResponse, ResponseEmitted> { firstResponse, secondResponse ->
                  //here you put your code
       return responseEmmitted
                  }
                }).subscribe({ response -> },{ })
    

    【讨论】:

      猜你喜欢
      • 2018-12-21
      • 2018-07-22
      • 1970-01-01
      • 1970-01-01
      • 2020-07-21
      • 2020-06-11
      • 2011-02-16
      • 2017-11-01
      • 2018-06-29
      相关资源
      最近更新 更多