Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
RXJS operator function to store a stream in localStorage, then replays from localStorage when provided BehaviourSubject is true. This is helpful if you need to replay a complicated set of observable streams after a browser redirect.
* Stores last emitted value in localStorage and replays if usStore$ is set.
* If usStore$ is truthy then switches stream to use stored value.
* If usStore$ is undefined then stream will emit as normal.
* @param storageKey unique key to use in localStorage
* @param useStore$ controls if the localStorage value is used
export default function localStorageReplay<T>(storageKey: string, useStore$: BehaviorSubject<boolean>): MonoTypeOperatorFunction<T> {
return (input$): Observable<T> => {
// Observable for parsed stored value, fallsback to input stream.
const storedValue$ = of(localStorage.getItem(`stream-${storageKey}`)).pipe(
map(str => (str === 'undefined' ? undefined : JSON.parse(str))),
catchError(() => input$)
// if useStore is true set then replay localStorage value
return useStore$.pipe(
switchMap(useStore =>
? storedValue$
: input$.pipe(tap(val => localStorage.setItem(`stream-${storageKey}`, JSON.stringify(val))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.