Callback when there are no subscribers
Closed this issue · 5 comments
Hello, I want to make an async store that automatically updates on notification froma server side (using websockets), but this case I need to call await ws.close()
when there are no more subscribers to the store, how can I achieve that?
Hi, not sure, but possible it would be better to use svelte-websocket-store for this purpose. It will call ws.close()
automatically for you.
Thank you for a reference, svelte-websocket-store is not what I need, because I use websockets only for notification that something changed and then I fetch the actual data using XHR. Anyway, I've already implemented what I need in my fork of svelte-asyncable
I'm not sure I fully understand you implementation, but I try to imagine how I would solve this problem (without fork and changing api of asyncable store):
const notificationUpdates = readable(null, set => {
const socket = new WebSocket(url, socketOptions);
...
return () => socket.close();
});
const notifications = asyncable(fetchNotifications, null, [ notificationUpdates ]);
It's not full and ready-to-use implementation, but I think the idea is clear - notificationUpdates
is a read-only store to control the state of websocket connection. It will initialized when asyncable store will get first subscriber and socket will be closed when there're no more subscribers of the asyncable store.
@nikicat Solution was found basically, I think we can close this issue. Feel free to re-open it when you needed.
Hmm, may be this will work if I set inner store to WebSocket object. Thank you for the idea!