如何使用rx Java一次压缩多个不同类型的observable?
Observable<Action> actionStream = getAction();
Observable<UserInfo> ownerStream = getOwner();
Observable<List<UserInfo>> relatedUsersStream = getUsers();
Observable<Double> score = getScore();
//Question: how to merge all relusts at once nad call `getResult`?
getResult(action, owner, relatedUsers, score);
更新:找到解决方案。但问题是getResult
返回Observable<Result>
而不是Result
,而zip方法不想编译。
Observable.<Action, UserInfo, List<UserInfo>, Double, Result>zip(
(action, owner, relatedUsers, score) -> getResult(action, owner, relatedUsers, score)
);
答案 0 :(得分:3)
rxjava-joins项目http://mvnrepository.com/artifact/io.reactivex/rxjava-joins/0.22.0包含和/ then / when功能。你可以做这样的事情:
@Test
public void rxJoins() throws Exception {
Observable<Integer> ints = Observable.just(1, 2, 3);
Observable<String> strs = Observable.just("a", "b", "c");
Observable<Boolean> bools = Observable.just(false, false, true);
Plan0<Data> threeItems = JoinObservable.from(ints).and(strs).and(bools).then(Data::new);
JoinObservable.when(threeItems).toObservable().toBlocking().subscribe(System.out::println);
}
private static class Data {
private final int val1;
private final String val2;
private final boolean val3;
public Data(int val1, String val2, boolean val3) {
this.val1 = val1;
this.val2 = val2;
this.val3 = val3;
}
@Override
public String toString() {
return "Data{" +
"val1=" + val1 +
", val2='" + val2 + '\'' +
", val3=" + val3 +
'}';
}
}
此处有更多信息:http://www.introtorx.com/content/v1.0.10621.0/12_CombiningSequences.html