RXJS modify order of subscribers

Viewed 212

Is it possible to ensure that a subscriber is the last to be executed in the observer queue? A delay(0) is no option for me since I need the code to be executed in line and not asynchrounus.

let observable = new Subject<void>();

//delay(0) no option!
observable.pipe().subscribe(() => console.log("I want to be last!"));
observable.subscribe(() => console.log("I want to be first!"));

observable.next();

I've created an example here: https://stackblitz.com/edit/rxjs-demo-xuf2ru

I want the first subscriber, to be executed last. The current console output is:

I want to be last!

I want to be first!

2 Answers

You may also use a common Subject as a means of communication between the observables as illustrated below:

const observable = new Subject<void>();
const commonSub$ = new Subject();

observable.pipe().subscribe(() => {
  commonSub$
    .subscribe(() => {
      console.log('I want to be last!');
    });
});

observable.subscribe(() => {
  console.log('I want to be first!');
  commonSub$.next(true);
});

observable.next();

Thereby, only after the second message is logged the first message will be logged.


As per your latest comment, you may use switchMap to ensure the same functionality is achieved for multiple events:

observable
   .switchMap(() => {
      return commonSub$;
   })
   .subscribe(() => {
      console.log("I want to be last!");
   });

observable.subscribe(() => {
   console.log("I want to be first!");
   commonSub$.next(true);
});

You could create 2 observables with the desired output and then use the mergeMap operator to preserve the order.

const observable1 = Observable.of("I want to be first!");
const observable2 = Observable.of("I want to be last!");

observable1
  .mergeMap(x => {
    console.log(x);
    return observable2;
  })
  .subscribe(x => console.log(x));

Stackblitz example

Related