Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

inject-is-restoring.ts

62 lines2.0 KB

1import {
2 InjectionToken,
3 Injector,
4 assertInInjectionContext,
5 inject,
6 signal,
7} from '@angular/core'
8import type { Provider, Signal } from '@angular/core'
9​
10/**
11 * Internal token used to track isRestoring state, accessible in public API
12 * through `injectIsRestoring` and set via `provideIsRestoring`
13 */
14const IS_RESTORING = new InjectionToken('', {
15 // Default value when not provided
16 factory: () => signal(false).asReadonly(),
17})
18​
19interface InjectIsRestoringOptions {
20 /**
21 * The `Injector` to use to get the isRestoring signal.
22 *
23 * If this is not provided, the current injection context will be used instead
24 * (via `inject`).
25 */
26 injector?: Injector
28​
29/**
30 * Injects a signal that tracks whether a restore (e.g. from a persisted client,
31 * wired up via `provideIsRestoring`) is currently in progress. `injectQuery`
32 * and friends also check this internally to avoid race conditions between the
33 * restore and initializing queries.
34 *
35 * @param options - Additional configuration
36 * @returns A readonly `Signal<boolean>` β€” `true` while a restore is in
37 * progress, `false` otherwise (the default when no `provideIsRestoring`
38 * provider is registered).
39 */
40export function injectIsRestoring(options?: InjectIsRestoringOptions) {
41 !options?.injector && assertInInjectionContext(injectIsRestoring)
42 const injector = options?.injector ?? inject(Injector)
43 return injector.get(IS_RESTORING)
45​
46/**
47 * Registers a provider for the restore state read by `injectIsRestoring`. Wire
48 * this up wherever you drive a restore yourself β€” e.g. a persist-client
49 * integration β€” so `injectQuery` and friends can defer subscribing to their
50 * observer (avoiding a race with the restore) until the restore signal flips
51 * back to `false`.
52 *
53 * @param isRestoring - A readonly `Signal<boolean>` that tracks the restore
54 * state.
55 * @returns A provider for the `isRestoring` signal.
56 */
57export function provideIsRestoring(isRestoring: Signal<boolean>): Provider {
58 return {
59 provide: IS_RESTORING,
60 useValue: isRestoring,
61 }