| 51 | * options (including no options) are batched together. |
| 52 | */ |
| 53 | export class IdleScheduler implements OnDestroy { |
| 54 | // Serialize options rather than using the object reference to ensure |
| 55 | // that different IdleRequestOptions references with the same values |
| 56 | // are batched into the same bucket. |
| 57 | private readonly buckets = new Map<string, IdleBucket>(); |
| 58 | |
| 59 | // Lookup from callback to its bucket key. |
| 60 | private readonly callbackBucket = new Map<VoidFunction, string>(); |
| 61 | private readonly applicationRef = inject(ApplicationRef); |
| 62 | |
| 63 | private readonly ngZone = inject(NgZone); |
| 64 | private readonly idleService = inject(IDLE_SERVICE); |
| 65 | |
| 66 | add(callback: VoidFunction, options?: IdleRequestOptions) { |
| 67 | const key = getIdleRequestKey(options); |
| 68 | this.callbackBucket.set(callback, key); |
| 69 | |
| 70 | let bucket = this.buckets.get(key); |
| 71 | if (bucket == null) { |
| 72 | bucket = {idleId: null, queue: new Set()}; |
| 73 | this.buckets.set(key, bucket); |
| 74 | } |
| 75 | bucket.queue.add(callback); |
| 76 | this.scheduleBucket(bucket, options); |
| 77 | } |
| 78 | |
| 79 | remove(callback: VoidFunction) { |
| 80 | const key = this.callbackBucket.get(callback); |
| 81 | if (key === undefined) return; |
| 82 | |
| 83 | this.callbackBucket.delete(callback); |
| 84 | |
| 85 | const bucket = this.buckets.get(key); |
| 86 | if (!bucket) return; |
| 87 | |
| 88 | bucket.queue.delete(callback); |
| 89 | |
| 90 | // If the last callback in this bucket was removed, cancel the |
| 91 | // idle callback - cancel it. |
| 92 | if (bucket.queue.size === 0) { |
| 93 | this.cancelBucket(bucket); |
| 94 | this.buckets.delete(key); |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | private scheduleBucket(bucket: IdleBucket, options?: IdleRequestOptions) { |
| 99 | if (bucket.idleId !== null) { |
| 100 | return; |
| 101 | } |
| 102 | |
| 103 | const key = getIdleRequestKey(options); |
| 104 | const callback = (deadline?: IdleDeadline) => { |
| 105 | this.cancelBucket(bucket); |
| 106 | |
| 107 | for (const cb of bucket.queue) { |
| 108 | cb(); |
| 109 | // _tick here is an optimized change detection check and is safe to call here. |
| 110 | // We also account for the time it takes to run change detection |
nothing calls this directly
no test coverage detected
searching dependent graphs…