Open History to see the last commit
1import {
2 DestroyRef,
3 assertInInjectionContext,
4 computed,
5 effect,
6 inject,
7 signal,
8 untracked,
9} from '@angular/core'
10import { injectQueryZone } from './inject-query-zone'
11import type { Signal, ValueEqualityFn } from '@angular/core'
12β
13interface ExternalBinding<T> {
14 /** Synchronous snapshot. Angular signals read here are tracked dependencies. */
15 readonly getSnapshot: () => T
16 /** Omit to pause observation; changing eligibility requires a new descriptor. */
17 readonly subscribe?: ((notify: () => void) => () => void) | undefined
18}
19β
20interface ExternalStoreOptions<T> {
21 /** Snapshot equality, defaulting to Object.is. Does not control connection identity. */
22 readonly equal?: ValueEqualityFn<T> | undefined
23}
24β
25/**
26 * Creates a readonly Angular signal backed by a synchronous external store.
27 *
28 * Store access, subscription setup, and cleanup run outside NgZone so background
29 * timers do not hold Angular stability open.
30 *
31 * Reads evaluate snapshots without subscribing. An effect owns the subscription
32 * and invalidates the snapshot after setup, closing the gap between an early
33 * read and connection. The next read recomputes the snapshot; equality prevents
34 * unchanged values from propagating. Unread snapshots stay lazy.
35 *
36 * Notifications invalidate snapshots synchronously once connected. Snapshot-only
37 * dependencies do not reinstall the subscription. Subscription setup and cleanup
38 * may read the returned signal; factories and snapshot readers must not recurse.
39 *
40 * Only factory/snapshot errors are exposed on reads. Subscription and cleanup
41 * errors follow Angular's normal effect error handling; the helper does not store
42 * them or implement retries. Destruction stops observation without changing the
43 * cached snapshot.
44 */
45export function injectExternalStore<T>(
46 binding: () => ExternalBinding<T>,
47 options?: ExternalStoreOptions<T>,
48): Signal<T> {
49 if (typeof ngDevMode === 'undefined' || ngDevMode) {
50 assertInInjectionContext(injectExternalStore)
51 }
52 const owner = inject(DestroyRef)
53 const outsideZone = injectQueryZone()
54 const revision = signal(0)
55 const requested = computed(() => outsideZone(binding))
56 const invalidate = () => untracked(() => revision.update((n) => n + 1))
57β
58 effect((onCleanup) => {
59 // The previous subscription's cleanup may have destroyed the owner.
60 if (owner.destroyed) return
61 const current = requested()
62 outsideZone(() =>
63 untracked(() => {
64 try {
65 const unsubscribe = current.subscribe?.(invalidate)
66 if (unsubscribe) {
67 // subscribe() can trigger component/injector destruction before returning.
68 // Registering cleanup afterward misses that destruction.
69 if (owner.destroyed) unsubscribe()
70 else onCleanup(() => outsideZone(unsubscribe))
71 }
72 } finally {
73 // Invalidate after subscribing so an early cached snapshot cannot miss
74 // changes before or during setup. Do not eagerly read the snapshot.
75 invalidate()
76 }
77 }),
78 )
79 })
80β
81 return computed(
82 () => {
83 revision()
84 return outsideZone(() => requested().getSnapshot())
85 },
86 options?.equal ? { equal: options.equal } : undefined,
87 )
88}