Pigelvy
Pigelvy

Reputation: 616

How to get 2 values from 2 differents RxJava Observables?

I have 2 Observables that will return only 1 thing. I need both values to do something else.

How can I subscribe to both Observables and receive a notification only when both values are available?

I tried something like:

   final Observable<String> obs1 = Observable.just("A", "B");
   final Observable<String> obs2 = Observable.just("A", "B");

   Observable.zip(
       obs1,
       obs2,
       (a, b) -> {
         System.out.println("Processing " + a + b);
         return null;
       }
   );

But nothing happens unless I register a subscriber (which would be useless).

The (ugly) solution I used is an embedded subscription such as:

   final Observable<String> obs1 = Observable.just("A", "B");
   final Observable<String> obs2 = Observable.just("A", "B");

   obs1.subscribe(
     a -> {
       obs2.subscribe(
         b -> {
           System.out.println("Processing " + a + b);
         }
       );
     }
   );

What is the way to do such a common thing?

Upvotes: 2

Views: 1212

Answers (1)

LordRaydenMK
LordRaydenMK

Reputation: 13321

Observables are lazy so you need a subscriber to do the work. To combine items from both observables you need to use the zip operator. Just one small modification to your first solution:

final Observable<String> obs1 = Observable.just("A", "B");
   final Observable<String> obs2 = Observable.just("A", "B");

   Observable.zip(
       obs1,
       obs2,
       (a, b) -> {
         System.out.println("Processing " + a + b);
         return null;
       }
   ).subscribe();

Upvotes: 4

Related Questions