Skip to content

Commit 62aeb53

Browse files
committed
feat(core): split tracking for effect and afterRenderEffect
Introduce a `splitTracking` helper to separate reactive tracking from non-reactive effect execution by isolating the reactive logic into a dedicated function. fixes #56155
1 parent 06b004e commit 62aeb53

4 files changed

Lines changed: 304 additions & 11 deletions

File tree

‎goldens/public-api/core/index.api.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1869,6 +1869,9 @@ export interface SkipSelfDecorator {
18691869
new (): SkipSelf;
18701870
}
18711871

1872+
// @public
1873+
export function splitTracking<T, Ret, Args extends any[]>(track: () => T, execute: (tracked: T, ...args: Args) => Ret): (...args: Args) => Ret;
1874+
18721875
// @public
18731876
export type StateKey<T> = string & {
18741877
__not_a_string: never;

‎packages/core/src/core_reactivity_export_internal.ts‎

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,23 +8,24 @@
88

99
export {SIGNAL as ɵSIGNAL} from '../primitives/signals';
1010

11+
export {afterRenderEffect, ɵFirstAvailableSignal} from './render3/reactivity/after_render_effect';
1112
export {isSignal, isWritableSignal, Signal, ValueEqualityFn} from './render3/reactivity/api';
13+
export {assertNotInReactiveContext} from './render3/reactivity/asserts';
1214
export {computed, CreateComputedOptions} from './render3/reactivity/computed';
13-
export {
14-
CreateSignalOptions,
15-
signal,
16-
WritableSignal,
17-
ɵunwrapWritableSignal,
18-
} from './render3/reactivity/signal';
19-
export {linkedSignal} from './render3/reactivity/linked_signal';
20-
export {untracked} from './render3/reactivity/untracked';
2115
export {
2216
CreateEffectOptions,
2317
effect,
24-
EffectRef,
2518
EffectCleanupFn,
2619
EffectCleanupRegisterFn,
20+
EffectRef,
2721
} from './render3/reactivity/effect';
22+
export {linkedSignal} from './render3/reactivity/linked_signal';
2823
export {EffectScheduler as ɵEffectScheduler} from './render3/reactivity/root_effect_scheduler';
29-
export {afterRenderEffect, ɵFirstAvailableSignal} from './render3/reactivity/after_render_effect';
30-
export {assertNotInReactiveContext} from './render3/reactivity/asserts';
24+
export {
25+
CreateSignalOptions,
26+
signal,
27+
WritableSignal,
28+
ɵunwrapWritableSignal,
29+
} from './render3/reactivity/signal';
30+
export {splitTracking} from './render3/reactivity/split_tracking';
31+
export {untracked} from './render3/reactivity/untracked';
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/**
2+
* @license
3+
* Copyright Google LLC All Rights Reserved.
4+
*
5+
* Use of this source code is governed by an MIT-style license that can be
6+
* found in the LICENSE file at https://angular.dev/license
7+
*/
8+
9+
import {untracked} from './untracked';
10+
11+
/**
12+
* Splits a reactive effect's tracking and side-effecting code, ensuring that the
13+
* side-effecting code doesn't implicitly track dependencies.
14+
*
15+
* @param track A function whose reactive reads will be tracked.
16+
* @param execute A function which receives the tracked value and the execution context arguments,
17+
* and runs in a non-tracking context.
18+
* @returns A function that combines the tracking and execution phases.
19+
*
20+
* @usageNotes
21+
*
22+
* ```ts
23+
* effect(
24+
* splitTracking(
25+
* () => mySignal(),
26+
* (mySignalValue, onCleanup) => {
27+
* // Execution phase: any signal reads here are untracked
28+
* console.log('Tracked values:', mySignalValue);
29+
* console.log('Untracked read:', untrackedSig());
30+
* }
31+
* )
32+
* );
33+
* ```
34+
*
35+
* Using `splitTracking` with `afterRenderEffect` phases:
36+
*
37+
* ```ts
38+
* afterRenderEffect({
39+
* earlyRead: () => {
40+
* return this.element.nativeElement.scrollWidth;
41+
* },
42+
* write: splitTracking(
43+
* // Tracking phase: tracks `isExpanded`
44+
* () => this.isExpanded(),
45+
* (isExpanded, scrollWidth, onCleanup) => {
46+
* // Execution phase: receives `isExpanded` from the track phase,
47+
* // and `scrollWidth` from the `earlyRead` phase.
48+
* // This block runs untracked, avoiding implicit dependencies on any reads.
49+
* if (isExpanded) {
50+
* this.element.nativeElement.style.width = `${scrollWidth}px`;
51+
* }
52+
* }
53+
* )
54+
* });
55+
* ```
56+
*
57+
* @publicApi 22.1
58+
*/
59+
export function splitTracking<T, Ret, Args extends any[]>(
60+
track: () => T,
61+
execute: (tracked: T, ...args: Args) => Ret,
62+
): (...args: Args) => Ret {
63+
return (...args: Args) => {
64+
const trackedValue = track();
65+
return untracked(() => execute(trackedValue, ...args));
66+
};
67+
}
Lines changed: 222 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,222 @@
1+
/**
2+
* @license
3+
* Copyright Google LLC All Rights Reserved.
4+
*
5+
* Use of this source code is governed by an MIT-style license that can be
6+
* found in the LICENSE file at https://angular.dev/license
7+
*/
8+
9+
import {TestBed} from '@angular/core/testing';
10+
import {
11+
afterRenderEffect,
12+
ApplicationRef,
13+
computed,
14+
effect,
15+
Injector,
16+
signal,
17+
Signal,
18+
} from '../../src/core';
19+
import {EffectCleanupRegisterFn} from '../../src/render3/reactivity/effect';
20+
import {splitTracking} from '../../src/render3/reactivity/split_tracking';
21+
22+
describe('splitTracking', () => {
23+
it('should track only the tracking function (effect)', () => {
24+
let effectCount = 0;
25+
const trackedValue = signal('tracked');
26+
const untrackedValue = signal('untracked');
27+
28+
effect(
29+
splitTracking(
30+
() => trackedValue(),
31+
(val: string) => {
32+
// Read untrackedValue to verify it's not tracked
33+
untrackedValue();
34+
effectCount++;
35+
},
36+
),
37+
{injector: TestBed.inject(Injector)},
38+
);
39+
40+
const appRef = TestBed.inject(ApplicationRef);
41+
appRef.tick();
42+
expect(effectCount).toBe(1);
43+
44+
untrackedValue.set('changed untracked');
45+
appRef.tick();
46+
expect(effectCount).toBe(1);
47+
48+
trackedValue.set('changed tracked');
49+
appRef.tick();
50+
expect(effectCount).toBe(2);
51+
});
52+
53+
it('should provide cleanup function for effect', () => {
54+
let cleanupCount = 0;
55+
let effectCount = 0;
56+
const trackedValue = signal('tracked');
57+
58+
effect(
59+
splitTracking(
60+
() => trackedValue(),
61+
(val: string, onCleanup: EffectCleanupRegisterFn) => {
62+
effectCount++;
63+
onCleanup(() => cleanupCount++);
64+
},
65+
),
66+
{injector: TestBed.inject(Injector)},
67+
);
68+
69+
const appRef = TestBed.inject(ApplicationRef);
70+
appRef.tick();
71+
expect(effectCount).toBe(1);
72+
expect(cleanupCount).toBe(0);
73+
74+
trackedValue.set('changed 1');
75+
appRef.tick();
76+
expect(effectCount).toBe(2);
77+
expect(cleanupCount).toBe(1);
78+
79+
trackedValue.set('changed 2');
80+
appRef.tick();
81+
expect(effectCount).toBe(3);
82+
expect(cleanupCount).toBe(2);
83+
});
84+
85+
it('should track only invoked signals', () => {
86+
let effectCount = 0;
87+
const sigA = signal('A');
88+
const sigB = signal('B');
89+
effect(
90+
splitTracking(
91+
() => [sigA, sigB] as const,
92+
([valA, valB]) => {
93+
// Those signals were not invoked before hands.
94+
valA();
95+
valB();
96+
effectCount++;
97+
},
98+
),
99+
{injector: TestBed.inject(Injector)},
100+
);
101+
102+
const appRef = TestBed.inject(ApplicationRef);
103+
appRef.tick();
104+
expect(effectCount).toBe(1);
105+
sigA.set('changed A');
106+
appRef.tick();
107+
expect(effectCount).toBe(1);
108+
sigB.set('changed B');
109+
appRef.tick();
110+
expect(effectCount).toBe(1);
111+
});
112+
113+
it('should work with afterRenderEffect without phases', () => {
114+
let effectCount = 0;
115+
const trackedValue = signal('tracked');
116+
const untrackedValue = signal('untracked');
117+
118+
afterRenderEffect(
119+
splitTracking(
120+
() => trackedValue(),
121+
(val: string) => {
122+
untrackedValue();
123+
effectCount++;
124+
},
125+
),
126+
{injector: TestBed.inject(Injector)},
127+
);
128+
129+
const appRef = TestBed.inject(ApplicationRef);
130+
appRef.tick();
131+
expect(effectCount).toBe(1);
132+
133+
untrackedValue.set('changed untracked');
134+
appRef.tick();
135+
expect(effectCount).toBe(1);
136+
137+
trackedValue.set('changed tracked');
138+
appRef.tick();
139+
expect(effectCount).toBe(2);
140+
});
141+
142+
it('should work with afterRenderEffect with phases', () => {
143+
let earlyReadCount = 0;
144+
let writeCount = 0;
145+
let cleanupCount = 0;
146+
const trackedValue = signal('tracked');
147+
const untrackedValue = signal('untracked');
148+
149+
afterRenderEffect(
150+
{
151+
earlyRead: () => {
152+
// early read is tracked
153+
trackedValue();
154+
earlyReadCount++;
155+
return 42;
156+
},
157+
write: splitTracking(
158+
// tracking fn
159+
() => trackedValue(),
160+
(val: string, earlyReadVal: Signal<number>, onCleanup: EffectCleanupRegisterFn) => {
161+
// non tracking execute fn
162+
untrackedValue();
163+
writeCount++;
164+
expect(earlyReadVal()).toBe(42);
165+
onCleanup(() => {
166+
cleanupCount++;
167+
});
168+
},
169+
),
170+
},
171+
{injector: TestBed.inject(Injector)},
172+
);
173+
174+
const appRef = TestBed.inject(ApplicationRef);
175+
appRef.tick();
176+
expect(earlyReadCount).toBe(1);
177+
expect(writeCount).toBe(1);
178+
expect(cleanupCount).toBe(0);
179+
180+
untrackedValue.set('changed untracked');
181+
appRef.tick();
182+
expect(earlyReadCount).toBe(1);
183+
expect(writeCount).toBe(1);
184+
expect(cleanupCount).toBe(0);
185+
186+
trackedValue.set('changed tracked');
187+
appRef.tick();
188+
expect(earlyReadCount).toBe(2);
189+
expect(writeCount).toBe(2);
190+
expect(cleanupCount).toBe(1);
191+
});
192+
193+
it('should work with computed', () => {
194+
let executeCount = 0;
195+
const trackedValue = signal('tracked');
196+
const untrackedValue = signal('untracked');
197+
198+
const result = computed(
199+
splitTracking(
200+
() => trackedValue(),
201+
(val: string) => {
202+
untrackedValue();
203+
executeCount++;
204+
return val + ' and ' + untrackedValue();
205+
},
206+
),
207+
);
208+
209+
expect(result()).toBe('tracked and untracked');
210+
expect(executeCount).toBe(1);
211+
212+
untrackedValue.set('changed untracked');
213+
// untracked changing should not trigger recomputation
214+
expect(result()).toBe('tracked and untracked');
215+
expect(executeCount).toBe(1);
216+
217+
trackedValue.set('changed tracked');
218+
// tracked changing should trigger recomputation, reading the new untracked value
219+
expect(result()).toBe('changed tracked and changed untracked');
220+
expect(executeCount).toBe(2);
221+
});
222+
});

0 commit comments

Comments
 (0)