[英]RxJava2 combine multiple observables to make them return single result
如何將 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<Integer> friendsIds;
我的目標是有一個這樣的方法:
public Observable<Feed> /*or Single<Feed>*/ getFeed(List<Integer> ids) {
...
}
它返回一個Observable
或Single
,它執行以下操作:
getUserPosts(idFromList)
到一個 observable 對於每個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())
));
}
此解決方案不包括頁面問題。 這就是為什么它只是部分解決方案
有許多運算符可以將事物轉換為其他事物。 fromIterable()
將發出可迭代對象中的每一項,而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);
如果您需要將兩個響應合二為一,則應使用 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 -> },{ })
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.