cyrilletuzi/angular-async-local-storage

Change event?

georgstrieder opened this issue · 3 comments

Is there a way to make the observable of getItem() listen, if a local storage item has changed? E.g. after setItem().

Can you provide a use case ?

Local storage won't change by itself, so if you want to listen storage modifications, you should create an observable in your own app.

For example :

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { AsyncLocalStorage } from 'angular-async-local-storage';

@Injectable()
export class SomeService {
  public storageStream = new BehaviorSubject({});
  public constructor(protected localStorage: AsyncLocalStorage) {}
  public save(key: string, value: any) {
    this.localStorage.setItem(key, value).subscribe(() => {
      this.storageStream.next({ key, value });
    });
  }
}

(It's just a quick example, BehaviorSubject may not be the best RxJS class for this case, and operations surely could be more linear.)

Closing, as no use case was provided.

Sorry if i up this issue,but i didn't understand very well how to listen changes to localstorage updates;

(EXAMPLE);i have a class that read object from localstorage,and a service that update local storage when needed (example when there are new content to download).

myclass:

liveCategories: Category[] =[];
constructor(protected localStorage: LocalStorage,private storageService:StorageService) {
    this.localStorage.getItem('LiveCategories').subscribe((cat) => {
      console.log('categories->',cat);
      this.liveCategories=cat;
      this.doRender=1;
    });
}

My service (StorageService):

..

constructor(protected localStorage:LocalStorage){}
...
//i call this function each time i want to reaload the category (ex:new content avaible)
private setLiveCategories(categories:Category[]){
    this.localStorage.setItem('LiveCategories', categories).subscribe(() => {
      console.log('Storage Service saved categories');
    });

  }

How i can update myClass.liveCategories when localStorage.liveCategories is changed?

Sorry for the boring question,but i'm a little bit "new" to rjxs programming.