如何在转换当前结果时等待另一个可观察的结果?
我有一个用户ID列表(userIdsList
),我应该将它们转换为地图。在map中,key由userId表示,value为boolean,表示userId是否包含regUsers
。
return Observable
.<List<Long>>from(userIdsList)
.groupBy(id -> id, id -> regUsers.contains(id)); //PROBLEM: regUsers is Observable<List<Long>>
答案 0 :(得分:1)
有点复杂的解决方案。
List<Long> ids = Arrays.asList(1L, 2L, 3L);
Observable<List<Long>> regUsers = Observable.just(Arrays.asList(1L, 2L)).cache();
Observable<Long> idsStream = Observable.from(ids).cache();
Observable<Boolean> containsStream = idsStream
.concatMap(id -> regUsers.map(regList -> regList.contains(id)));
idsStream.zipWith(containsStream, (Func2<Long, Boolean, Pair>) Pair::new)
.toMap(Pair::getLeft, Pair::getRight).subscribe(System.out::println);
private static class Pair<K, V> {
private final K left;
private final V right;
public Pair(K left, V right) {
this.left = left;
this.right = right;
}
public K getLeft() {
return left;
}
public V getRight() {
return right;
}
}