Home > Software design >  How to wait for function with observable to resolve?
How to wait for function with observable to resolve?

Time:01-14

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.

CodePudding user response:

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

CodePudding user response:

Assuming your buildData is complete after you get a response, one of the solutions would be returning new promise, from buildData, and resolving it same time you handle response.

buildData() {
  return new Promise((resolve, reject) => {
    this.services.getData()
      .pipe(takeUntil(this.ngUnsubscribe))
      .subscribe(response => {
        resolve(response);
        this.handleResponse(response);
      });
  });
}


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