Skip to content

Commit 0914100

Browse files
committed
fix subscribe implementation, add test for unsubscribing observables
1 parent c4a8e97 commit 0914100

File tree

4 files changed

+69
-6
lines changed

4 files changed

+69
-6
lines changed

src/internal/utils.js

+5-6
Original file line numberDiff line numberDiff line change
@@ -48,12 +48,11 @@ export function validate_store(store, name) {
4848
}
4949

5050
export function subscribe(component, store, callback) {
51-
let unsub = store.subscribe(callback);
52-
// Prevent memory leaks for RxJS users.
53-
if (unsub.unsubscribe) {
54-
unsub = () => unsub.unsubscribe();
55-
}
56-
component.$$.on_destroy.push(unsub);
51+
const unsub = store.subscribe(callback);
52+
53+
component.$$.on_destroy.push(unsub.unsubscribe
54+
? () => unsub.unsubscribe()
55+
: unsub);
5756
}
5857

5958
export function create_slot(definition, ctx, fn) {
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
<script>
2+
export let observable;
3+
</script>
4+
5+
<p>value: {$observable}</p>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
const subscribers = [];
2+
3+
let value = 'initial';
4+
5+
const observable = {
6+
subscribe: fn => {
7+
subscribers.push(fn);
8+
9+
fn(value);
10+
11+
return {
12+
unsubscribe: () => {
13+
const i = subscribers.indexOf(fn);
14+
subscribers.splice(i, 1);
15+
}
16+
};
17+
}
18+
};
19+
20+
export default {
21+
props: {
22+
observable,
23+
visible: false
24+
},
25+
26+
html: ``,
27+
28+
async test({ assert, component, target }) {
29+
assert.equal(subscribers.length, 0);
30+
31+
component.visible = true;
32+
33+
assert.equal(subscribers.length, 1);
34+
assert.htmlEqual(target.innerHTML, `
35+
<p>value: initial</p>
36+
`);
37+
38+
value = 42;
39+
await subscribers.forEach(fn => fn(value));
40+
41+
assert.htmlEqual(target.innerHTML, `
42+
<p>value: 42</p>
43+
`);
44+
45+
component.visible = false;
46+
47+
assert.equal(subscribers.length, 0);
48+
}
49+
};
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
<script>
2+
import Nested from './Nested.svelte';
3+
4+
export let observable;
5+
export let visible;
6+
</script>
7+
8+
{#if visible}
9+
<Nested {observable}/>
10+
{/if}

0 commit comments

Comments
 (0)