Skip to content

Commit 628b04d

Browse files
committed
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".
1 parent 93f7ecc commit 628b04d

File tree

1 file changed

+7
-2
lines changed

1 file changed

+7
-2
lines changed

src/internal/utils.js

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,12 @@ export function validate_store(store, name) {
4848
}
4949

5050
export function subscribe(component, store, callback) {
51-
component.$$.on_destroy.push(store.subscribe(callback));
51+
let unsub = store.subscribe(callback);
52+
// Prevent memory leaks for RxJS users.
53+
if (typeof unsub === 'object' && typeof unsub.unsubscribe === 'function') {
54+
unsub = () => unsub.unsubscribe();
55+
}
56+
component.$$.on_destroy.push(unsub);
5257
}
5358

5459
export function create_slot(definition, ctx, fn) {
@@ -74,4 +79,4 @@ export function exclude_internal_props(props) {
7479
const result = {};
7580
for (const k in props) if (k[0] !== '$') result[k] = props[k];
7681
return result;
77-
}
82+
}

0 commit comments

Comments
 (0)