How to wait for function with observable to resolve?

325 views Asked by At

Working on Angular/Angular2 and I've got something like

buildData() {
this.services.getData()).pipe(takeUntil(this.ngUnsubscribe))
    .subscribe(response => {
        this.handleResponse(response);
})


handleEvent($event) {
const value = this.value;
this.buildData();
//Do some stuff here after buildData is finished. 
}

What I don't know is how to wait until buildData() finishes.

I tried adding an await

handleEvent($event) {
const value = this.value;
await this.buildData();
//Do some stuff here after buildData is finished. 
}

But it doesn't work since it doesnt return a promise.

1

There are 1 answers

0
Mathias Ravelojaona On

I suggest you use a pipe with the tap operator to trigger your side effect then return the observable so you can subscribe on it later or trigger other side effects from it

buildData() {
  return this.services.getData()).pipe(takeUntil(this.ngUnsubscribe))
    .pipe(
      tap((data) => this.handleResponse(response))
    );
})


handleEvent($event) {
  const value = this.value;
  this.buildData()
    .pipe(
      //your operations
    ).subscribe();
}