2

This is the marble diagram for a RxJs swithmap function.

Reference: https://rxjs.dev/api/operators/switchMap

My questions are:

  1. What is the large space between 1 & 3 and small space between 3 & 5 mean? Is it duration in seconds between those numbers when they are emitted?
  2. In this diagram, what are inner observable and outer observable?
  3. The last line shows 30 and 50 together. Why the third 30 disappeared?
  4. More confusing to me is the following code. The output is consistent and print all 9 values. The result is not 8 values like shown in the marble diagram where some values like 30 is ignored.

const switched = of(1, 2, 3).pipe(switchMap(x => of(x, x ** 2, x ** 3)));
switched.subscribe(x => console.log(x));
// outputs
// 1
// 1
// 1
// 2
// 4
// 8
// 3
// 9
// 27

enter image description here

wonderful world
  • 10,969
  • 20
  • 97
  • 194

1 Answers1

1
  1. The space indeed represents time, for instance it could be time between http response
  2. The inner observable is the result return by the function in switchMap and of(1, 2, 3) would be the outer one
  3. swithMap uses most recent values. In this case 5 arrives before the third 3 * 10 is taken into account so it is skipped
  4. In your example you don't have time really taken into account

Below would be a more accurate representation of your diagram

  result: number[] = [];

  sourceA$ = new Observable<number>((subscriber) => subscriber.next(10));

  sourceB$ = new Observable<number>((subscriber) => {
    subscriber.next(1);

    setTimeout(() => subscriber.next(1), 1000);

    setTimeout(() => subscriber.next(1), 2000);

    setTimeout(() => subscriber.next(3), 4000);

    setTimeout(() => subscriber.next(3), 5000);

    setTimeout(() => subscriber.next(5), 6000);

    setTimeout(() => subscriber.next(5), 7000);
    
    setTimeout(() => subscriber.next(5), 8000);

    setTimeout(() => subscriber.complete(), 10000);
  });

  target$ = this.sourceB$.pipe(
    switchMap((x) => this.sourceA$.pipe(tap((y) => this.result.push(x * y))))
  );

  constructor() {
    this.target$.subscribe();
  }

You should use this marble diagrams they are interactive and might help you more

PasNinii
  • 634
  • 8
  • 18