vach
vach

Reputation: 11377

RxJava zip with vararg observables

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

Upvotes: 3

Views: 4204

Answers (1)

ArturoTena
ArturoTena

Reputation: 795

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

Upvotes: 3

Related Questions