Better way to cache an expensive Observable source? #7546
Answered
by
alexanderharding
thomasnield
asked this question in
Q&A
-
I have this code below that demonstrates a caching replayable Observable that updates every 2 seconds. It also will shut down when there are no subscribers, but will rebuild once there are new subscribers. Is there a better way to do this? Or is there an existing operator I'm not using? import {
of,
interval,
shareReplay,
tap,
toArray,
switchMap,
take,
delay,
mergeMap,
} from 'rxjs';
// refresh cache every 2 seconds
const source = interval(2000)
.pipe(
switchMap(_ => of('A', 'B', 'C', 'D', 'E').pipe(
toArray(),
tap((_) => console.log('Data refreshed'))
)
)
)
.pipe(shareReplay({ bufferSize: 1, refCount: true }), take(1));
// These subscribers should use the same cache
source.subscribe((x) => console.log(`SUBSCRIBER 1: ${x}`));
of('Start')
.pipe(
delay(500),
mergeMap((_) => source)
)
.subscribe((x) => console.log(`SUBSCRIBER 2: ${x}`));
of('Start')
.pipe(
delay(1500),
mergeMap((_) => source)
)
.subscribe((x) => console.log(`SUBSCRIBER 3: ${x}`));
// These subscribers should trigger a rebuild and reuse of the next cache
of('Start')
.pipe(
delay(5000),
mergeMap((_) => source)
)
.subscribe((x) => console.log(`SUBSCRIBER 4: ${x}`));
of('Start')
.pipe(
delay(6500),
mergeMap((_) => source)
)
.subscribe((x) => console.log(`SUBSCRIBER 5: ${x}`)); |
Beta Was this translation helpful? Give feedback.
Answered by
alexanderharding
Apr 12, 2025
Replies: 1 comment 2 replies
-
Sure, it looks like you want a cache that implements the stale-while-revalidate pattern but only while there are subscribers.
I have more examples of other caching strategies that leverage other operators if you'd like to see. |
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
thomasnield
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sure, it looks like you want a cache that implements the stale-while-revalidate pattern but only while there are subscribers.