Here is the minimal code that reproduces the problem:
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();
I would expect to only see one number logged. Not hundreds.
The problem disappears if you do any of the following things:
- remove
shareReplay(1) - you don't use the
cacheobject, but just useoneRandomNumber.pipe(shareReplay(1))directly - don't use
switchMaptwice
But my eventual code needs all of those things.