LynxSessionStorage

A key-value store that every page of your app shares while the app runs. import { LynxSessionStorage, type SessionStorageSubscription } from '@blotch/angular-lynx';

Each page is a separate LynxView (one Lynx screen inside the host app), and this store is how they share state.

Usage

src/app/counter.ts
import { Component, inject } from '@angular/core';
import { LYNX_ELEMENTS, LynxSessionStorage } from '@blotch/angular-lynx';

@Component({
  selector: 'app-counter',
  imports: [LYNX_ELEMENTS],
  template: `
    <view (bindtap)="increment()">
      <text>Count: {{ count() ?? 0 }}</text>
    </view>
  `,
})
export class Counter {
  readonly #storage = inject(LynxSessionStorage);
  readonly count = this.#storage.watch<number>('count');

  increment(): void {
    this.#storage.setItem('count', (this.count() ?? 0) + 1);
  }
}

API

LynxSessionStorage

@Injectable({ providedIn: 'root' })
class LynxSessionStorage {}

Stores values for the life of the app session, not across restarts. Unlike localStorage, values can be objects and numbers as well as strings, and reads are asynchronous.

  • Outside the native app, such as in the web preview and unit tests, it falls back to an in-memory store.

LynxSessionStorage.setItem()

setItem<T = unknown>(key: string, value: T): void;

Stores value under key and notifies subscribers to that key.

LynxSessionStorage.getItem()

getItem<T = unknown>(key: string): Promise<T>;

Resolves with the value stored under key.

LynxSessionStorage.subscribe()

subscribe<T = unknown>(
  key: string,
  callback: (value: T) => void,
): SessionStorageSubscription;

Calls callback with the new value each time key is set. Returns the subscription to pass to unsubscribe().

LynxSessionStorage.unsubscribe()

unsubscribe(subscription: SessionStorageSubscription): void;

Stops a subscription.

LynxSessionStorage.watch()

watch<T = unknown>(
  key: string,
  options?: { injector?: Injector },
): WritableSignal<T | undefined>;

Returns a signal that holds the key's value. It starts as undefined, fills in with the stored value, then follows later writes, with the limit below.

  • Injection context: call it in a constructor or field initializer, or pass options.injector. The subscription ends when that injector is destroyed.
  • Read it, don't set it. Setting the signal doesn't write to storage. Use setItem().
Other pages' writes don't reach the screen

On a device, Lynx notifies subscribers about other pages' writes only on the background thread. On the main thread, which draws the UI, subscribe() and watch() see only this page's own setItem() calls, so watch() doesn't show another page's later writes. See Threads.

Types

SessionStorageSubscription

type SessionStorageSubscription = {
  readonly key: string;
  readonly listenerId: number;
};

The handle that subscribe() returns. Treat it as opaque.