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

inject-pending-tasks-lifecycle.ts

41 lines1.1 KB

1import { DestroyRef, NgZone, PendingTasks, inject } from '@angular/core'
2​
3export interface QueryLifecycle {
4 readonly destroyed: boolean
5 setPending: (pending: boolean) => void
6}
7​
8/** Tracks pending work for the lifetime of the current injection context. */
9export function injectPendingTasksLifecycle(): QueryLifecycle {
10 const destroyRef = inject(DestroyRef)
11 const pendingTasks = inject(PendingTasks)
12 const ngZone = inject(NgZone)
13 let taskCleanup: (() => void) | undefined
14​
15 const lifecycle: QueryLifecycle = {
16 get destroyed() {
17 return destroyRef.destroyed
18 },
19 setPending(pending) {
20 if (pending) {
21 if (!destroyRef.destroyed && !taskCleanup) {
22 taskCleanup = pendingTasks.add()
23 }
24 return
25 }
26​
27 const cleanup = taskCleanup
28 taskCleanup = undefined
29 // Enter NgZone while our task is still held to avoid transient stability
30 // before dependent queries are scheduled.
31 // In zoneless apps, NgZone.run simply invokes the cleanup.
32 if (cleanup) ngZone.run(cleanup)
33 },
34 }
35​
36 destroyRef.onDestroy(() => {
37 lifecycle.setPending(false)
38 })
39​
40 return lifecycle