Make StorageApi notify its subscribers when localStorage values change in other tabs/windows

Signed-off-by: Dawit Ameneshewa <dawitam11@gmail.com>
This commit is contained in:
Dawit Ameneshewa
2022-12-06 10:11:45 +03:00
parent 325ebb0b34
commit 1018dcdd4a
@@ -89,9 +89,19 @@ export class WebStorage implements StorageApi {
observe$<T extends JsonValue>(
key: string,
): Observable<StorageValueSnapshot<T>> {
this.addStorageEventListener();
return this.observable.filter(({ key: messageKey }) => messageKey === key);
}
private addStorageEventListener() {
window.addEventListener('storage', event => {
if (event.key?.includes(this.namespace)) {
const key = event.key.replace(`${this.namespace}/`, '');
this.notifyChanges(key);
}
});
}
private getKeyName(key: string) {
return `${this.namespace}/${encodeURIComponent(key)}`;
}