Open History to see the last commit
1import { DestroyRef, NgZone, PendingTasks, inject } from '@angular/core'
2β
3/**
4 * Tracks ownership and pending work for the current Angular injection context.
5 */
6export interface QueryLifecycle {
7 /**
8 * Whether Angular has destroyed the injection context that owns this query.
9 */
10 readonly destroyed: boolean
11 /**
12 * Adds or releases the task that keeps Angular unstable while owned work is pending.
13 */
14 setPending: (pending: boolean) => void
15}
16β
17/**
18 * Tracks pending work for the lifetime of the current injection context.
19 * @returns The destruction state and pending-task controller for this context.
20 */
21export function injectPendingTasksLifecycle(): QueryLifecycle {
22 const destroyRef = inject(DestroyRef)
23 const pendingTasks = inject(PendingTasks)
24 const ngZone = inject(NgZone)
25 let taskCleanup: (() => void) | undefined
26β
27 const lifecycle: QueryLifecycle = {
28 get destroyed() {
29 return destroyRef.destroyed
30 },
31 setPending(pending) {
32 if (pending) {
33 if (!destroyRef.destroyed && !taskCleanup) {
34 taskCleanup = pendingTasks.add()
35 }
36 return
37 }
38β
39 const cleanup = taskCleanup
40 taskCleanup = undefined
41 // Enter NgZone while our task is still held to avoid transient stability
42 // before dependent queries are scheduled.
43 // In zoneless apps, NgZone.run simply invokes the cleanup.
44 if (cleanup) ngZone.run(cleanup)
45 },
46 }
47β
48 destroyRef.onDestroy(() => {
49 lifecycle.setPending(false)
50 })
51β
52 return lifecycle
53}