How to check if multiple subscriptions reached onComplete()?

Viewed 2642

I have two subscriptions in an Angular 6 component. Now I want to start a method as soon as these two subscriptions reached onComplete.

How can I do this the easiest way?

4 Answers

Use forkJoin. It will emit as soon as all given Observables completed.

You can use forkJoin to wait for both once both are done, then you subscribe to it as you would normally do with an observable.

Like so

import { Component } from '@angular/core';
import { forkJoin, Observable } from 'rxjs'

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';

 constructor(){
   forkJoin([this.observableTest(2000), this.observableTest(3000)])
   .subscribe(data => {
     this.runMeAfter(data)
   })
 }

  runMeAfter(data){
    alert('yeahhh done with data, check your console for data')
    console.log(data)
  }

  observableTest(delay){
    return Observable.create(observer => {
      setTimeout(() => {
        observer.next("data to send can be object or anything");
        console.log("am done");
        observer.complete(); // to show we are done with our processing 
      }, delay);
    })
  }
}

The runMeAfter will be called as soon as both asynchronous codes are done with the processing.

Stackblitz demo: https://stackblitz.com/edit/angular-forkjoin-theo

We can use merge operator which allows us to subscribe multiple observables in parallel.

const stream1$ = of (1,2,3);
    const stream2$ = of (4,5,6);
    const result$ = merge(stream1$, stream2$);
    result$.subscribe(
// value
      (val) => {console.log(val) },
// error
    (err) => { console.log(err) },
//on complete
    ()=>{console.log('completed') });

forkJoin works when all the obserables have emitted one value. Similar to promise.All.

If the obserables are going to emit more than one value. You can use combineLatest which emits a value each time all the obserables have emitted one value.

Related