-
Notifications
You must be signed in to change notification settings - Fork 25.1k
/
effect.ts
304 lines (266 loc) · 9.47 KB
/
effect.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {createWatch, Watch, WatchCleanupRegisterFn} from '@angular/core/primitives/signals';
import {ChangeDetectorRef} from '../../change_detection';
import {assertInInjectionContext} from '../../di/contextual';
import {InjectionToken} from '../../di/injection_token';
import {Injector} from '../../di/injector';
import {inject} from '../../di/injector_compatibility';
import {ɵɵdefineInjectable} from '../../di/interface/defs';
import {ErrorHandler} from '../../error_handler';
import type {ViewRef} from '../view_ref';
import {DestroyRef} from '../../linker/destroy_ref';
import {FLAGS, LViewFlags, EFFECTS_TO_SCHEDULE} from '../interfaces/view';
import {assertNotInReactiveContext} from './asserts';
/**
* An effect can, optionally, register a cleanup function. If registered, the cleanup is executed
* before the next effect run. The cleanup function makes it possible to "cancel" any work that the
* previous effect run might have started.
*
* @developerPreview
*/
export type EffectCleanupFn = () => void;
/**
* A callback passed to the effect function that makes it possible to register cleanup logic.
*
* @developerPreview
*/
export type EffectCleanupRegisterFn = (cleanupFn: EffectCleanupFn) => void;
export interface SchedulableEffect {
run(): void;
creationZone: unknown;
}
/**
* Not public API, which guarantees `EffectScheduler` only ever comes from the application root
* injector.
*/
export const APP_EFFECT_SCHEDULER = new InjectionToken('', {
providedIn: 'root',
factory: () => inject(EffectScheduler),
});
/**
* A scheduler which manages the execution of effects.
*/
export abstract class EffectScheduler {
/**
* Schedule the given effect to be executed at a later time.
*
* It is an error to attempt to execute any effects synchronously during a scheduling operation.
*/
abstract scheduleEffect(e: SchedulableEffect): void;
/** @nocollapse */
static ɵprov = /** @pureOrBreakMyCode */ ɵɵdefineInjectable({
token: EffectScheduler,
providedIn: 'root',
factory: () => new ZoneAwareMicrotaskScheduler(),
});
}
/**
* Interface to an `EffectScheduler` capable of running scheduled effects synchronously.
*/
export interface FlushableEffectRunner {
/**
* Run any scheduled effects.
*/
flush(): void;
}
/**
* An `EffectScheduler` which is capable of queueing scheduled effects per-zone, and flushing them
* as an explicit operation.
*/
export class ZoneAwareQueueingScheduler implements EffectScheduler, FlushableEffectRunner {
private queuedEffectCount = 0;
private queues = new Map<Zone|null, Set<SchedulableEffect>>();
scheduleEffect(handle: SchedulableEffect): void {
const zone = handle.creationZone as Zone | null;
if (!this.queues.has(zone)) {
this.queues.set(zone, new Set());
}
const queue = this.queues.get(zone)!;
if (queue.has(handle)) {
return;
}
this.queuedEffectCount++;
queue.add(handle);
}
/**
* Run all scheduled effects.
*
* Execution order of effects within the same zone is guaranteed to be FIFO, but there is no
* ordering guarantee between effects scheduled in different zones.
*/
flush(): void {
while (this.queuedEffectCount > 0) {
for (const [zone, queue] of this.queues) {
// `zone` here must be defined.
if (zone === null) {
this.flushQueue(queue);
} else {
zone.run(() => this.flushQueue(queue));
}
}
}
}
private flushQueue(queue: Set<SchedulableEffect>): void {
for (const handle of queue) {
queue.delete(handle);
this.queuedEffectCount--;
// TODO: what happens if this throws an error?
handle.run();
}
}
/** @nocollapse */
static ɵprov = /** @pureOrBreakMyCode */ ɵɵdefineInjectable({
token: ZoneAwareQueueingScheduler,
providedIn: 'root',
factory: () => new ZoneAwareQueueingScheduler(),
});
}
/**
* A wrapper around `ZoneAwareQueueingScheduler` that schedules flushing via the microtask queue
* when.
*/
export class ZoneAwareMicrotaskScheduler implements EffectScheduler {
private hasQueuedFlush = false;
private delegate = new ZoneAwareQueueingScheduler();
private flushTask = () => {
// Leave `hasQueuedFlush` as `true` so we don't queue another microtask if more effects are
// scheduled during flushing. The flush of the `ZoneAwareQueueingScheduler` delegate is
// guaranteed to empty the queue.
this.delegate.flush();
this.hasQueuedFlush = false;
// This is a variable initialization, not a method.
// tslint:disable-next-line:semicolon
};
scheduleEffect(handle: SchedulableEffect): void {
this.delegate.scheduleEffect(handle);
if (!this.hasQueuedFlush) {
queueMicrotask(this.flushTask);
this.hasQueuedFlush = true;
}
}
}
/**
* Core reactive node for an Angular effect.
*
* `EffectHandle` combines the reactive graph's `Watch` base node for effects with the framework's
* scheduling abstraction (`EffectScheduler`) as well as automatic cleanup via `DestroyRef` if
* available/requested.
*/
class EffectHandle implements EffectRef, SchedulableEffect {
unregisterOnDestroy: (() => void)|undefined;
readonly watcher: Watch;
constructor(
private scheduler: EffectScheduler,
private effectFn: (onCleanup: EffectCleanupRegisterFn) => void,
public creationZone: Zone|null, destroyRef: DestroyRef|null,
private errorHandler: ErrorHandler|null, allowSignalWrites: boolean) {
this.watcher = createWatch(
(onCleanup) => this.runEffect(onCleanup), () => this.schedule(), allowSignalWrites);
this.unregisterOnDestroy = destroyRef?.onDestroy(() => this.destroy());
}
private runEffect(onCleanup: WatchCleanupRegisterFn): void {
try {
this.effectFn(onCleanup);
} catch (err) {
this.errorHandler?.handleError(err);
}
}
run(): void {
this.watcher.run();
}
private schedule(): void {
this.scheduler.scheduleEffect(this);
}
destroy(): void {
this.watcher.destroy();
this.unregisterOnDestroy?.();
// Note: if the effect is currently scheduled, it's not un-scheduled, and so the scheduler will
// retain a reference to it. Attempting to execute it will be a no-op.
}
}
/**
* A global reactive effect, which can be manually destroyed.
*
* @developerPreview
*/
export interface EffectRef {
/**
* Shut down the effect, removing it from any upcoming scheduled executions.
*/
destroy(): void;
}
/**
* Options passed to the `effect` function.
*
* @developerPreview
*/
export interface CreateEffectOptions {
/**
* The `Injector` in which to create the effect.
*
* If this is not provided, the current [injection context](guide/dependency-injection-context)
* will be used instead (via `inject`).
*/
injector?: Injector;
/**
* Whether the `effect` should require manual cleanup.
*
* If this is `false` (the default) the effect will automatically register itself to be cleaned up
* with the current `DestroyRef`.
*/
manualCleanup?: boolean;
/**
* Whether the `effect` should allow writing to signals.
*
* Using effects to synchronize data by writing to signals can lead to confusing and potentially
* incorrect behavior, and should be enabled only when necessary.
*/
allowSignalWrites?: boolean;
}
/**
* Create a global `Effect` for the given reactive function.
*
* @developerPreview
*/
export function effect(
effectFn: (onCleanup: EffectCleanupRegisterFn) => void,
options?: CreateEffectOptions): EffectRef {
ngDevMode &&
assertNotInReactiveContext(
effect,
'Call `effect` outside of a reactive context. For example, schedule the ' +
'effect inside the component constructor.');
!options?.injector && assertInInjectionContext(effect);
const injector = options?.injector ?? inject(Injector);
const errorHandler = injector.get(ErrorHandler, null, {optional: true});
const destroyRef = options?.manualCleanup !== true ? injector.get(DestroyRef) : null;
const handle = new EffectHandle(
injector.get(APP_EFFECT_SCHEDULER), effectFn,
(typeof Zone === 'undefined') ? null : Zone.current, destroyRef, errorHandler,
options?.allowSignalWrites ?? false);
// Effects need to be marked dirty manually to trigger their initial run. The timing of this
// marking matters, because the effects may read signals that track component inputs, which are
// only available after those components have had their first update pass.
//
// We inject `ChangeDetectorRef` optionally, to determine whether this effect is being created in
// the context of a component or not. If it is, then we check whether the component has already
// run its update pass, and defer the effect's initial scheduling until the update pass if it
// hasn't already run.
const cdr = injector.get(ChangeDetectorRef, null, {optional: true}) as ViewRef<unknown>| null;
if (!cdr || !(cdr._lView[FLAGS] & LViewFlags.FirstLViewPass)) {
// This effect is either not running in a view injector, or the view has already
// undergone its first change detection pass, which is necessary for any required inputs to be
// set.
handle.watcher.notify();
} else {
// Delay the initialization of the effect until the view is fully initialized.
(cdr._lView[EFFECTS_TO_SCHEDULE] ??= []).push(handle.watcher.notify);
}
return handle;
}