Skip to content
This repository has been archived by the owner on Jul 29, 2023. It is now read-only.

Commit

Permalink
fix: defer local storage querying
Browse files Browse the repository at this point in the history
The method obtained the value before the stream was observed. Fixed this in order to get the latest value at the time of subscription.
  • Loading branch information
chernodub committed Nov 23, 2022
1 parent d4d0142 commit da00964
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
15 changes: 15 additions & 0 deletions projects/ngx-lss/src/lib/ngx-local-storage.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,21 @@ describe('NgxLocalStorageService', () => {
expect(resultValues).toContain(secondData);
}));

it('should return latest value at the time of subscription', () => {
const testKey = 'some-key';
const latestDummyData = { someNewData: 12345 };

const resultValues: unknown[] = [];

spectator.service.save(testKey, { someData: 123 }).subscribe();
const data$ = spectator.service.get(testKey);
spectator.service.save(testKey, latestDummyData).subscribe();
data$.subscribe(data => resultValues.push(data));

expect(resultValues.length).toBe(1);
expect(resultValues).toContain(latestDummyData);
});

it('returns initial null in case storage is empty', () => {
const key = 'some-non-existent-key';
const observerSpy = createObserverSpy();
Expand Down
9 changes: 7 additions & 2 deletions projects/ngx-lss/src/lib/ngx-local-storage.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,14 @@ export class NgxLocalStorageService {
* @param key Unique key.
*/
public get<T = unknown>(key: string): Observable<T | null> {
return this.watchStorageChangeByKey(key).pipe(
const initialValue$ = defer(() => of(this.obtainFromStorageByKey<T>(key)));
const valueChanges$ = this.watchStorageChangeByKey(key).pipe(
map(() => this.obtainFromStorageByKey<T>(key)),
startWith(this.obtainFromStorageByKey<T>(key)),
);
return merge(
initialValue$,
valueChanges$,
).pipe(
shareReplay({ refCount: true, bufferSize: 1 }),
);
}
Expand Down

0 comments on commit da00964

Please sign in to comment.