How to invoke another function only when both the callback inside a function is invoked and remaining part of the function is executed?

Viewed 152

My Angular Code

getStatus(transferDTO){
  this.queryResourceService.getInventoryStatusIdByStatusNameAndStatusTypeUsingGET(transferDTO).subscribe(
    this.save()
  );
  /*
  Remaining code here 
  */
  this.save()
}

function save() {
}

Now I don't want to call this.save() twice, I want it to be invoked only after the callback is executed as well as remaining code in the method is executed... Of course, I can get around this problem as follows

getStatus(transferDTO){
  /*
  Remaining code here 
  */
  this.queryResourceService.getInventoryStatusIdByStatusNameAndStatusTypeUsingGET(transferDTO).subscribe(this.save());
}

save(){

}

but I don't want to delay the callback method. So how can I solve this problem?

2 Answers

You could abuse the startWith() operator to do achieve it. From the docs

Returns an Observable that emits the items you specify as arguments before it begins to emit items emitted by the source Observable.

Try the following

import { startWith } from 'rxjs/operators';

getStatus (transferDTO) {
  this.queryResourceService.getInventoryStatusIdByStatusNameAndStatusTypeUsingGET(transferDTO)
    .pipe(startWith(0))
    .subscribe(
      response => {
        if (response === 0) {
          // run some independent code
        } else {
          // run dependent code
          this.save()
        }
      },
      error => { // handle error }
    );
}

Make sure the value passed to startWith() doesn't resemble the actual value returned by the source observable.

If you just want getInventoryStatusIdByStatusNameAndStatusTypeUsingGET and the "Remaining code" to execute in parallel, and then call save() when both complete, you can just wrap your "Remaining code" in an Observable and use forkJoin to execute both Observables in parallel.

Something like this:

getStatus(transferDTO) {
  const getStatusId$ = this.queryResourceService.getInventoryStatusIdByStatusNameAndStatusTypeUsingGET(transferDTO);
  const remainingCode$ = this.getRemainingCode();

  forkJoin(
    getStatusId$,
    remainingCode$
  ).subscribe(res => {
    this.save();
  });
}

getRemainingCode(): Observable<null> {
  return new Observable(subscriber => {
    /*
    Remaining code here 
    */
    subscriber.next();
    subscriber.complete();
  })
}

Here's a stackblitz

Related