RxJava zip with vararg observables

妖精的绣舞 提交于 2019-12-12 16:02:04

问题


When we know exactly how many observables we have with their exact types and we want to zip we do like this

Observable<String> data1 = Observable.just("one", "two", "three", "four", "five");
Observable<String> data2 = Observable.just("one", "two", "three", "four", "five");
Observable<String> data3 = Observable.just("one", "two", "three", "four", "five");

Observable.zip(data1, data2, data3, (a, b, c) -> a + b + c);

we use fixed argument functional interface which takes 3 arguments... and it works ok in this case.

but if we know that we have some N number of Observable<T> where T is the same type how do we zip it? consumer funtion can be something that takes T...

but i dont see any way to implement this...

UPDATE

Practical problem i'm trying to solve here is that i have some number of Observable<T> and i want to forkJoin those and chose only one T in the end to emit...

Imagine several observables emiting T that i want to take and compare and emit only one with some other observable...

SOLUTION

As said in answer there is a zip that takes an iterable and a function, sample code looks like this

Observable<String> data1 = Observable.just("one", "two", "three", "four", "five");
Observable<String> data2 = Observable.just("one", "two", "three", "four", "five");
Observable<String> data3 = Observable.just("one", "two", "three", "four", "five");
List<Observable<String>> iter = Arrays.asList(data1, data2, data3);

Observable.zip(iter, args1 -> args1).subscribe((arg)->{
  for (Object o : arg) {
    System.out.println(o);
  }
});

which will produce

one
one
one
two
two
two
three
three
three
four
four
four
five
five
five

回答1:


There is a zip method which takes an Iterable. That would allow to use n Observables.



来源:https://stackoverflow.com/questions/28958631/rxjava-zip-with-vararg-observables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!