Last active
January 27, 2023 10:51
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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) | |
); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ho can I use it in a real get ?