Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way like Promise.all() in RxJava?

I have a question.

I need to get list of some items by a list of the item ids. At first, I tried

Observable.from(itemIds)
  .flatMap(itemId -> requestToServer(itemId))
  .subscribe(item -> { /* do something */ });

But the operator flatMap does not guarantee the order of items. I need to get item in order that ItemIds have.

It would be great if there was the api like Promise.all(). Is there a way like Promise.all() in RxJava? or any other ways?

like image 857
chooblarin Avatar asked Feb 11 '16 12:02

chooblarin


2 Answers

It sounds like you're looking for the Zip operator

For example:

Observable<Integer> obs1 = Observable.just(1);
Observable<String> obs2 = Observable.just("Blah");
Observable<Boolean> obs3 = Observable.just(true);

Observable.zip(obs1, obs2, obs3, (Integer i, String s, Boolean b) -> i + " " + s + " " + b)
 .subscribe(str -> System.out.println(str));

prints:

1 Blah true

like image 198
Malt Avatar answered Oct 24 '22 21:10

Malt


Use concatMap instead. That will concatenate the emitted Observables in order rather than merging their emissions

Returns a new Observable that emits items resulting from applying a function that you supply to each item emitted by the source Observable, where that function returns an Observable, and then emitting the items that result from concatinating those resulting Observables.

like image 22
Thorn G Avatar answered Oct 24 '22 20:10

Thorn G