fix subscribe implementation, add test for unsubscribing observables

pull/2577/head
Richard Harris 5 years ago
parent c4a8e9755f
commit 091410028e

@ -48,12 +48,11 @@ export function validate_store(store, name) {
}
export function subscribe(component, store, callback) {
let unsub = store.subscribe(callback);
// Prevent memory leaks for RxJS users.
if (unsub.unsubscribe) {
unsub = () => unsub.unsubscribe();
}
component.$$.on_destroy.push(unsub);
const unsub = store.subscribe(callback);
component.$$.on_destroy.push(unsub.unsubscribe
? () => unsub.unsubscribe()
: unsub);
}
export function create_slot(definition, ctx, fn) {

@ -0,0 +1,5 @@
<script>
export let observable;
</script>
<p>value: {$observable}</p>

@ -0,0 +1,49 @@
const subscribers = [];
let value = 'initial';
const observable = {
subscribe: fn => {
subscribers.push(fn);
fn(value);
return {
unsubscribe: () => {
const i = subscribers.indexOf(fn);
subscribers.splice(i, 1);
}
};
}
};
export default {
props: {
observable,
visible: false
},
html: ``,
async test({ assert, component, target }) {
assert.equal(subscribers.length, 0);
component.visible = true;
assert.equal(subscribers.length, 1);
assert.htmlEqual(target.innerHTML, `
<p>value: initial</p>
`);
value = 42;
await subscribers.forEach(fn => fn(value));
assert.htmlEqual(target.innerHTML, `
<p>value: 42</p>
`);
component.visible = false;
assert.equal(subscribers.length, 0);
}
};

@ -0,0 +1,10 @@
<script>
import Nested from './Nested.svelte';
export let observable;
export let visible;
</script>
{#if visible}
<Nested {observable}/>
{/if}
Loading…
Cancel
Save