以给定方式组合RxJava中的2个可观察对象

时间:2017-11-01 07:03:02

标签: rx-java

我想组合以下列方式发出的2个可观察对象,我希望得到如下所示的结果:

                  Timeline ->

Observable 1:     A    B    C
Observable 2:                 1

Desired result: A1 B1 C1

CombineLatest只给我C1,Zip只提供A1。不确定我应该使用哪个操作员。

2 个答案:

答案 0 :(得分:0)

我会尝试类似的东西 -

        final Observable<String> letters = ...
        final Observable<Integer> numbers = ...

        final ConnectableObservable<Integer> sharedNumbers = numbers.publish();
        final Observable<List<String>> bufferedLetters = letters.buffer(sharedNumbers);
        final Observable<Pair<Integer, List<String>>> buffers = Observable.combineLatest(sharedNumbers, bufferedLetters, new Func2<Integer, List<String>, Pair<Integer, List<String>>>() {
            @Override
            public Pair<Integer, List<String>> call(Integer number, List<String> letters) {
                return new Pair<>(number, letters);
            }
        });
        final Observable<Pair<Integer, String>> pairs = buffers.flatMap(new Func1<Pair<Integer, List<String>>, Observable<Pair<Integer, String>>>() {
            @Override
            public Observable<Pair<Integer, String>> call(final Pair<Integer, List<String>> buffer) {
                return Observable.from(buffer.second).map(new Func1<String, Pair<Integer, String>>() {
                    @Override
                    public Pair<Integer, String> call(String letter) {
                        return new Pair<>(buffer.first, letter);
                    }
                });
            }
        });
        sharedNumbers.connect();

答案 1 :(得分:0)

您需要缓冲Observable1发出的所有项目,并将其与每个Observable2项目组合在一起。这是我的代码:

BehaviorSubject<String> s1 = BehaviorSubject.create();
BehaviorSubject<String> s2 = BehaviorSubject.create();
Observable.combineLatest(s1.scan(new ArrayList<>(), (l, s) -> {
  l.add(s);
  return l;
}), s2, (list, s) -> Observable.fromIterable(list).map(a -> a + s))
    .concatMap(o -> o)
    .subscribe(System.out::println);
s1.onNext("a");
s1.onNext("b");
s1.onNext("c");
s2.onNext("1");

并输出:

a1
b1
c1