Thorsten Westheider
Thorsten Westheider

Reputation: 10932

How can I wait for 2 observables with different return types?

I need to wait on 2 observables to process a request, the types of which are different, e.g.

observable1 = Observable.create((observer: Subscriber<Type1> => ...)

and

observable2 = Observable.create((observer: Subscriber<Type2> => ...)

How can I avoid nested subscriptions such as

observable1.subscribe(result1 => {
    observable2.subscribe(result2 => {
        ...
        <do something with result1 and result2>
        ...
    }
}

I tried

observable1.concat(observable2).subscribe(result => ...)

but that appears to read from both observables in turn.

I'm thinking along the lines of

observable1<???>observable2.subscribe((result1, result2) => ...)

How can I do that?

Upvotes: 1

Views: 476

Answers (1)

Matt Burnell
Matt Burnell

Reputation: 2796

You're correct: concat will read from the observables in turn. To "join" them (by ordinal position), you will want to use zip:

const a$ = Rx.Observable.just(1);
const b$ = Rx.Observable.just(2);

const combined$ = a$.zip(b$, (x, y) => ({ a: x, b: y }));

const subscription = combined$.subscribe(x => console.log(x));

Note that the fact that the two streams are of different types causes no inconvenience when using zip, as a function must be provided to produce a new value from the two "zipped" values.

Upvotes: 1

Related Questions