user1007817
user1007817

Reputation:

Single Success Callback with RxJS Observables

How can I have a single success callback with observables while allowing each single observable to have its own success/error block? I have a dynamic list of AJAX calls which need to be made and each one requires it's on callback method. I'd also would like to have a single callback method after every AJAX call completes. I've tried using zip, but AJAX calls are called twice.

Example:

var possibleRequest1 = Observable.create(() => {}).subscribe(_ => {
    //Must have a success callback
});
var possibleRequest2 = Observable.create(() => {}).subscribe(_ => {
    //Must have a success callback
});
var possibleRequest3 = Observable.create(() => {}).subscribe(_ => {
    //Must have a success callback
});

//User 1 might need to make requests 1 and 2
var dynamicRequstList = [possibleRequest1, possibleRequest2];
//User 2 might need to make all three requests
var dynamicRequstList = [possibleRequest1, possibleRequest2, possibleRequest3];

zip(...dynamicRequestList)
.subscribe(() => {
    //Need a callback after all requests are complete.
});

Upvotes: 2

Views: 384

Answers (1)

Abylay
Abylay

Reputation: 344

You can use forkJoin from rxjs. Here example how use forkJoin on the example of your question.

service.ts

constructor(private http: HttpClient) { }

requestList1$ = new Subject();
requestList2$ = new Subject();

getDynamicRequstList1() {
    forkJoin(
      this.getItems1(),
      this.getItems2()
    ).subscribe(res => this.requestList1$.next(res));
}

getDynamicRequstList2() {
    forkJoin(
      this.getItems1(),
      this.getItems2(),
      this.getItems3()
    ).subscribe(res => this.requestList2$.next(res));
}  

getItems1(): Observable<any> {
    return of({
      item1: 'Item 1'
    });
}  

getItems2(): Observable<any> {
    return of({
      item1: 'Item 2'
    });
  }  

getItems3(): Observable<any> {
    return of({
      item1: 'Item 3'
    });
}

component.ts

constructor(private service: AppService) { }

ngOnInit() {
  this.service.requestList1$.subscribe(res => console.log('RES 1:::', res))
  this.service.requestList2$.subscribe(res => console.log('RES 2:::', res))
}

Upvotes: 2

Related Questions