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 * @param binding - Produces the current snapshot reader and optional subscription.
45 * @param options - Optional equality comparison for snapshots.
46 * @returns A readonly signal containing the latest external snapshot.
47 */
48export function injectExternalStore<T>(
49 binding: () => ExternalBinding<T>,
50 options?: ExternalStoreOptions<T>,
51): Signal<T> {
52 if (typeof ngDevMode === 'undefined' || ngDevMode) {
53 assertInInjectionContext(injectExternalStore)
54 }
55 const owner = inject(DestroyRef)
56 const outsideZone = injectQueryZone()
57 const revision = signal(0)
58 const requested = computed(() => outsideZone(binding))
59 const invalidate = () => untracked(() => revision.update((n) => n + 1))
60β
61 effect((onCleanup) => {
62 // The previous subscription's cleanup may have destroyed the owner.
63 if (owner.destroyed) return
64 const current = requested()
65 outsideZone(() =>
66 untracked(() => {
67 try {
68 const unsubscribe = current.subscribe?.(invalidate)
69 if (unsubscribe) {
70 // subscribe() can trigger component/injector destruction before returning.
71 // Registering cleanup afterward misses that destruction.
72 if (owner.destroyed) unsubscribe()
73 else onCleanup(() => outsideZone(unsubscribe))
74 }
75 } finally {
76 // Invalidate after subscribing so an early cached snapshot cannot miss
77 // changes before or during setup. Do not eagerly read the snapshot.
78 invalidate()
79 }
80 }),
81 )
82 })
83β
84 return computed(
85 () => {
86 revision()
87 return outsideZone(() => requested().getSnapshot())
88 },
89 options?.equal ? { equal: options.equal } : undefined,
90 )
91}