5

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?

2 Answers 2

9

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

1

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.

3
  • Yes, but concatMap processes the request one by one. What I want to do is that all requests are concurrent, but all responses are in order. as Promise.all() do.
    – chooblarin
    Feb 11, 2016 at 12:49
  • Perhaps this article will help? Haven't tried this trick w/ concatMap though, so not sure: tomstechnicalblog.blogspot.com/2015/11/…
    – Dan Lew
    Feb 11, 2016 at 14:45
  • I found concatMapEager operator. This is what I need, maybe. Thanks!
    – chooblarin
    Feb 11, 2016 at 17:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.