Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[experiment] effect guards #126

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions src/tests/integration/effect-test.gts
Original file line number Diff line number Diff line change
Expand Up @@ -134,4 +134,25 @@ module('Integration | Internal | effect', function () {
);
assert.equal(executionsCount, 3, `executions count not changed`);
});
test('check loop guard', async function (assert) {
const source = cell(1);
const derived = cell(1);
let executionsCount = 0;
const destructor = effect(() => {
derived.update(source.value);
source.value = Math.random();
executionsCount++;
console.log('effect executed');
});
assert.notEqual(derived.value, source.value);
assert.equal(executionsCount, 1, `effect executed once`);
source.update(2);
await rerender();
assert.notEqual(derived.value, source.value);
assert.equal(executionsCount, 2, `effect executed second time`);
await rerender();
assert.equal(executionsCount, 2, `effect executed second time`);

destructor();
});
});
18 changes: 17 additions & 1 deletion src/utils/vm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
formula,
opsFor,
inNewTrackingFrame,
tagsToRevalidate,
} from './reactive';
import { isFn } from './shared';

Expand All @@ -34,7 +35,22 @@ export function effect(cb: () => void): () => void {
const tag = formula(() => {
runEffectDestructor(destructor);
destructor = undefined;
return sourceTag.value;
if (import.meta.env.DEV) {
const value = sourceTag.value;
try {
return value;
} finally {
if (import.meta.env.DEV) {
for (const tag of tagsToRevalidate) {
if (sourceTag.relatedCells?.has(tag)) {
throw new Error(`effect mutating its source: ${tag._debugName} ${JSON.stringify(tag._value)}`)
}
}
}
}
} else {
return sourceTag.value;
}
}, 'effect');
const destroyOpcode = opcodeFor(tag, (value: unknown) => {
if (IS_DEV_MODE) {
Expand Down
Loading