fix: Ensure RxJS users don't create memory leaks

There is a bit of excitement in the RxJS community about Svelte.

- It seems like the rest of Svelte "just works™" with RxJS!
- **BUT** The danger is that unwary users will figure out how smooth this API is and accidentally create nasty memory leaks if the returned RxJS Subscriptions are not handled. Fortunately the required change is small.

NOTE: I am not entirely sure how to test this change. The goal here is to make sure that whenever you would normally teardown your store subscriptions, it is also tearing down these RxJS-shaped subscriptions. This is most commonly something you want in a component scenario. Say you have a timer component in your app that you show and remove with an `{#if}` block, when the `{#if}` block hides the component, you'd want to tear down the underlying Observable that is "ticking".

Related #2549
pull/2556/head
Ben Lesh 5 years ago
parent 93f7ecca1d
commit e25b7df275

@ -48,7 +48,12 @@ export function validate_store(store, name) {
}
export function subscribe(component, store, callback) {
component.$$.on_destroy.push(store.subscribe(callback));
let unsub = store.subscribe(callback);
// Prevent memory leaks for RxJS users.
if (typeof unsub === 'object' && typeof unsub.unsubscribe === 'function') {
unsub = () => unsub.unsubscribe();
}
component.$$.on_destroy.push(unsub);
}
export function create_slot(definition, ctx, fn) {
@ -74,4 +79,4 @@ export function exclude_internal_props(props) {
const result = {};
for (const k in props) if (k[0] !== '$') result[k] = props[k];
return result;
}
}

Loading…
Cancel
Save