Making an observable 'run' synchronously

2.3k Views Asked by At

I have a situation in which I need to wait for the observable to begin emitting values before the subsequent code executes. The closest I have gotten so far is like this:

async ensureContentLoaded() {
  if (!this.content) {
    defer(async () => {
      this.content = await this.getContent();
      console.log(`Got content`);
    }).subscribe();

    console.log(`Finished`);
  }

At the moment, the Finished console log is appearing before the Got content. I want the observable to 'block' until it starts to emit values. Note that this.getContent() returns a promise; although it could easily return an observable if that makes any difference. Also I know that this.content is referring to the wrong context, but that's another issue.

How can I create an observable that will block execution until a value is emitted?

1

There are 1 best solutions below

0
Fan Cheung On

THe following code should be sufficient.

ensureContentLoaded() {
  if (this.content) return of(this.content);
  return from(this.getContent());
}
// usage 
this.ensureContentLoaded().subscribe(console.log);
// or turn it to promise if needed
this.ensureContentLoaded().pipe(toPromise()).then(...)