Skip to content

Instantly share code, notes, and snippets.

@JonCatmull
Last active January 27, 2023 10:51
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JonCatmull/1f671d0071f61a9c225c6368a67b225d to your computer and use it in GitHub Desktop.
Save JonCatmull/1f671d0071f61a9c225c6368a67b225d to your computer and use it in GitHub Desktop.
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 =>
useStore
? storedValue$
: input$.pipe(tap(val => localStorage.setItem(`stream-${storageKey}`, JSON.stringify(val))))
),
shareReplay(1)
);
};
}
@sunsgs
Copy link

sunsgs commented Jan 27, 2023

Ho can I use it in a real get ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment