Check out the code snippet below for reproducing the issue:
import { defer, BehaviorSubject, of } from "rxjs";
import { shareReplay, switchMap } from "rxjs/operators";
const oneRandomNumber = defer(() => of(Math.floor(Math.random() * 20)));
const cache = { key: oneRandomNumber.pipe(shareReplay(1)) };
export const swr = () =>
new BehaviorSubject(null).pipe(
switchMap(() => cache.key),
switchMap(number => {
console.log(number); // WHY DOES THIS EXECUTE SO MANY TIMES?!
return cache.key;
})
);
swr().subscribe();
The expected behavior is to only see one number logged, not hundreds.
The issue can be resolved by undertaking any of the following actions:
- eliminate
shareReplay(1)
- bypass using the
cache
object and directly useoneRandomNumber.pipe(shareReplay(1))
- limit the usage of
switchMap
twice
However, all those elements are necessary in my final code implementation.