Alexandre Annic
Alexandre Annic

Reputation: 10788

How to await an asynchonous method defined inside subscribe before to complete an Rxjs Observable?

Let's take the code bellow:

myObservable.subscribe({
  next: async () => {
    await something();
  },
  complete: () => {
    console.log('All async task are comlpeted');
  }
});

The problem is that the console.log is called after the last next is triggered but I want it to be called after the last something() is finished.

Is there any way to do that ?

I specify that I implemented the myObservable by myself using new Obsercable(observer => ...). So it could be modified.

Upvotes: 2

Views: 569

Answers (1)

mbojko
mbojko

Reputation: 14699

I would either a) stick to the observable recipe, and convert promises to observables, or b) stick to the promise/async-await pattern, and convert observables to promises. I frankly have no idea how to successfully mix those two.

Rx-based solution:

import { from } from 'rxjs';
import { finalize } from 'rxjs/operators';

myObservable.pipe(
    switchMap(() => from(something()),
    finalize(() => console.log('All async task are comlpeted')),
).subscribe(someFunction);

Upvotes: 1

Related Questions