Skip to content

Commit 31352b6

Browse files
feat: add untrack, untrackScope (#25)
1 parent 2ac30ce commit 31352b6

File tree

3 files changed

+41
-4
lines changed

3 files changed

+41
-4
lines changed

Diff for: src/effect.ts

+11
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,17 @@ export let activeSub: Subscriber | undefined;
55
export let activeTrackId = 0;
66
export let lastTrackId = 0;
77

8+
export function untrack<T>(fn: () => T): T {
9+
const prevSub = activeSub;
10+
const prevTrackId = activeTrackId;
11+
setActiveSub(undefined, 0);
12+
try {
13+
return fn();
14+
} finally {
15+
setActiveSub(prevSub, prevTrackId);
16+
}
17+
}
18+
819
export function setActiveSub(sub: Subscriber | undefined, trackId: number): void {
920
activeSub = sub;
1021
activeTrackId = trackId;

Diff for: src/effectScope.ts

+18-4
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,22 @@ import { endTrack, Link, startTrack, Subscriber, SubscriberFlags } from './syste
44
export let activeEffectScope: EffectScope | undefined = undefined;
55
export let activeScopeTrackId = 0;
66

7+
export function untrackScope<T>(fn: () => T): T {
8+
const prevSub = activeEffectScope;
9+
const prevTrackId = activeScopeTrackId;
10+
setActiveScope(undefined, 0);
11+
try {
12+
return fn();
13+
} finally {
14+
setActiveScope(prevSub, prevTrackId);
15+
}
16+
}
17+
18+
export function setActiveScope(sub: EffectScope | undefined, trackId: number): void {
19+
activeEffectScope = sub;
20+
activeScopeTrackId = trackId;
21+
}
22+
723
export function effectScope(): EffectScope {
824
return new EffectScope();
925
}
@@ -34,13 +50,11 @@ export class EffectScope implements Subscriber {
3450
run<T>(fn: () => T): T {
3551
const prevSub = activeEffectScope;
3652
const prevTrackId = activeScopeTrackId;
37-
activeEffectScope = this;
38-
activeScopeTrackId = this.trackId;
53+
setActiveScope(this, this.trackId);
3954
try {
4055
return fn();
4156
} finally {
42-
activeEffectScope = prevSub;
43-
activeScopeTrackId = prevTrackId;
57+
setActiveScope(prevSub, prevTrackId);
4458
}
4559
}
4660

Diff for: tests/untrack.spec.ts

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import { untrack } from '../src';
2+
import { signal, computed } from './api';
3+
import { expect, test } from 'vitest';
4+
5+
test('should untrack', () => {
6+
const src = signal(0);
7+
const c = computed(() => untrack(() => src.get()));
8+
expect(c.get()).toBe(0);
9+
10+
src.set(1);
11+
expect(c.get()).toBe(0);
12+
});

0 commit comments

Comments
 (0)