TheUnreal
TheUnreal

Reputation: 24492

Angular 2 - Run 2 subscription in the same time

I have the following code:

//Subscription 3: role ID to role Name
        af.database.object('/roles/'+businessRole.$value)
        .subscribe((roleData) => {
        //Subscription 4: Get user info
        af.database.object('/users/'+businessRole.$key).subscribe(user => {

Which contains a subscription inside a subscription.

The problem here is that the app waiting for the first one before running the second one. I want to execute both of them in one time, and get the result of each. How I can do that?

I've been using Promise.All() before but:

  1. I would love to know how I can do that with rxjs
  2. I couldn't find a way to get the result of each observable using Promise.All()

Thanks

Upvotes: 0

Views: 2996

Answers (2)

martin
martin

Reputation: 96979

This creates two Observables that complete after 1000ms and 900ms. When you run this demo you'll see that the first one completes just a moment after the first one to prove that these we're executed in parallel.

let obs1 = Observable.of('HTTP Response 1').delay(1000);
let obs2 = Observable.of('HTTP Response 2').delay(900);

console.log('Start');

obs1.merge(obs2)
    .subscribe(val => console.log(val), undefined, () => console.log('Completed'));

See live demo: http://plnkr.co/edit/hzmpclxDkIhnfTYcWXd5?p=preview

This prints to console:

Start
HTTP Response 2
HTTP Response 1
Completed

If you need forkJoin(), then see my previous answer Observable.forkJoin() doesn't executes :).

Upvotes: 2

Kerim Emurla
Kerim Emurla

Reputation: 1151

I believe Observable.forkJoin is exactly what you need to be using in your situation.

This is how your code would look like using forkJoin:

Observable.forkJoin(
this.http.get('/roles/'+businessRole.$value).map((response: Response) => res.json()),
this.http.get('/users/'+businessRole.$key).map((response: Response) => res.json())
).subscribe(data => {
  data[0] // this will contain roleData
  data[1] // this will contain user
},
error => console.log(error));

This is a useful link where you can learn more about observables and how to use forkJoin.

Upvotes: 5

Related Questions