Skip to content

fix: derived store restarting when unsubscribed from another store with a shared ancestor #8368

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

Merged
merged 2 commits into from
Mar 14, 2023
Merged
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
10 changes: 7 additions & 3 deletions src/runtime/store/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ export function derived<T>(stores: Stores, fn: Function, initial_value?: T): Rea
const auto = fn.length < 2;

return readable(initial_value, (set) => {
let inited = false;
let started = false;
const values = [];

let pending = 0;
Expand All @@ -188,7 +188,7 @@ export function derived<T>(stores: Stores, fn: Function, initial_value?: T): Rea
(value) => {
values[i] = value;
pending &= ~(1 << i);
if (inited) {
if (started) {
sync();
}
},
Expand All @@ -197,12 +197,16 @@ export function derived<T>(stores: Stores, fn: Function, initial_value?: T): Rea
})
);

inited = true;
started = true;
sync();

return function stop() {
run_all(unsubscribers);
cleanup();
// We need to set this to false because callbacks can still happen despite having unsubscribed:
// Callbacks might already be placed in the queue which doesn't know it should no longer
// invoke this derived store.
started = false;
};
});
}
Expand Down
19 changes: 19 additions & 0 deletions test/store/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -407,6 +407,25 @@ describe('store', () => {
const d = derived(fake_observable, _ => _);
assert.equal(get(d), 42);
});

it('doesn\'t restart when unsubscribed from another store with a shared ancestor', () => {
const a = writable(true);
let b_started = false;
const b = derived(a, (_, __) => {
b_started = true;
return () => {
assert.equal(b_started, true);
b_started = false;
};
});
const c = derived(a, ($a, set) => {
if ($a) return b.subscribe(set);
});

c.subscribe(() => { });
a.set(false);
assert.equal(b_started, false);
});
});

describe('get', () => {
Expand Down