Skip to content

Commit

Permalink
fix(effectScope): should trigger inner effects in sequence
Browse files Browse the repository at this point in the history
  • Loading branch information
johnsoncodehk committed Oct 9, 2024
1 parent 6c6e867 commit c53b897
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 5 deletions.
14 changes: 12 additions & 2 deletions lib/effectScope.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,25 @@
import { DirtyLevels, Subscriber } from './system';
import { DirtyLevels, IEffect, Subscriber } from './system';

export function effectScope() {
return new EffectScope();
}

export class EffectScope implements Subscriber {
export class EffectScope implements IEffect, Subscriber {
nextNotify = undefined;

// Subscriber
deps = undefined;
depsTail = undefined;
versionOrDirtyLevel = DirtyLevels.NotDirty;

notify() {
const dirtyLevel = this.versionOrDirtyLevel;
if (dirtyLevel === DirtyLevels.MaybeDirty || dirtyLevel === DirtyLevels.Dirty) {
Subscriber.resolveMaybeDirty(this);
this.versionOrDirtyLevel = DirtyLevels.NotDirty;
}
}

run<T>(fn: () => T) {
const prevActiveSub = Subscriber.startScopeTrack(this);
const res = fn();
Expand Down
4 changes: 2 additions & 2 deletions lib/system.ts
Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,7 @@ export namespace Subscriber {

const system = System;

export function resolveMaybeDirty(sub: Dependency & Subscriber) {
export function resolveMaybeDirty(sub: Subscriber) {
let link = sub.deps;
let hasDirtyInnerEffects = false;

Expand Down Expand Up @@ -362,7 +362,7 @@ export namespace Subscriber {

if (prevLink !== undefined) {
if (dirtyLevel === DirtyLevels.Dirty) {
sub.update!();
(sub as Dependency & Subscriber).update!();
}

subSubs.prevSubOrUpdate = undefined;
Expand Down
32 changes: 31 additions & 1 deletion tests/effect.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { expect, test } from 'vitest';
import { computed, effect, signal, Subscriber, System } from '..';
import { computed, effect, effectScope, signal, Subscriber, System } from '..';

test('should clear subscriptions when untracked by all subscribers', () => {
const src = signal(1);
Expand Down Expand Up @@ -114,3 +114,33 @@ test('should trigger inner effects in sequence', () => {

expect(order).toEqual(['first inner', 'last inner']);
});

test('should trigger inner effects in sequence in effect scope', () => {
const a = signal(0);
const b = signal(0);
const scope = effectScope();
const order: string[] = [];

scope.run(() => {

effect(() => {
order.push('first inner');
a.get();
});

effect(() => {
order.push('last inner');
a.get();
b.get();
});
});

order.length = 0;

System.startBatch();
b.set(1);
a.set(1);
System.endBatch();

expect(order).toEqual(['first inner', 'last inner']);
});

0 comments on commit c53b897

Please sign in to comment.