How to check if multiple subscriptions reached onComplete()?

╄→гoц情女王★ 提交于 2019-12-24 01:06:42

问题


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?


回答1:


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




回答2:


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




回答3:


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') });



回答4:


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.



来源:https://stackoverflow.com/questions/52316084/how-to-check-if-multiple-subscriptions-reached-oncomplete

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!