如何组合最佳可观察<可观察<t>&gt;?

时间:2017-06-29 11:23:11

标签: java rx-java rx-java2

我有Observable<Observable<String>> c。我想将每个内部Observable合并为一个String和新行。结果应为Observable<String>

有一个similar discussion for RxJS on GitHub

以下是使用zip的实现:

final Observable<String> d = Observable.zip(c, objects -> Arrays.stream(objects)
    .map(x -> (String)x)
    .collect(Collectors.joining("\n")));

问题在于zip对元素,所以如果内部Observable对象具有不同的长度,那么不会显示所有内容。我想改用combineLatest,但似乎没有匹配函数:

public static <T, R> Observable<R> combineLatest(
    ObservableSource<? extends ObservableSource<? extends T>> sources, 
    Function<? super Object[], ? extends R> zipper)

我该如何实现?

例如,如果我有三个可观察量:

// a
Observable.just("Started", "0%", "5%", "10%", "20%", "40%", "95%", "100%", "Finished")

// b 
Observable.just("Started", "0%", "10%", "30%", "40%", "100%", "Finished")

// c
Observable.just("Started", "0%", "20%", "25%", "40%", "70%", "90%", "100%", "Finished")

然后我的zip解决方案的输出是:

---------------------
a: Started
b: Started
c: Started
---------------------
a: 0%
b: 0%
c: 0%
---------------------
a: 5%
b: 10%
c: 20%
---------------------
a: 10%
b: 30%
c: 25%
---------------------
a: 20%
b: 40%
c: 40%
---------------------
a: 40%
b: 100%
c: 70%
---------------------
a: 95%
b: Finished
c: 90%

但是所需的输出类似于:

---------------------
a: Started
b: Started
c: Started
---------------------
a: 0%
b: 0%
c: 0%
---------------------
a: 5%
b: 10%
c: 20%
---------------------
a: 10%
b: 30%
c: 25%
---------------------
a: 20%
b: 40%
c: 40%
---------------------
a: 40%
b: 100%
c: 70%
---------------------
a: 95%
b: Finished
c: 90%
---------------------
a: 100%
b: Finished
c: 100%
---------------------
a: Finished
b: Finished
c: Finished

1 个答案:

答案 0 :(得分:0)

使用RxJava2(和Java 8)

c.toList().toObservable()
          .flatMap(t -> 
                  Observable.combineLatest(t, 
                                           objects -> Arrays.stream(objects)
                                                            .map(x ->(String)x).collect(Collectors.joining("\n"))))

使用RxJava

c.toList().flatMap(t -> 
                  Observable.combineLatest(t, 
                                           objects -> Arrays.stream(objects)
                                                            .map(x -> (String)x).collect(Collectors.joining("\n"))));

我怀疑它会完全符合您的要求,因为它完全有可能“跳过”排放,但这就是combineLatest的工作方式。