razshare / sveltekit-sse

Server Sent Events with SvelteKit
https://www.npmjs.com/package/sveltekit-sse
MIT License
301 stars 9 forks source link

How to close SSE connection on client when destroying component? #24

Closed bluepuma77 closed 9 months ago

bluepuma77 commented 9 months ago

Hi Razvan, your library is really moving fast, hard to keep up with my simple sveltekit-sse-chat-example, but it helps a lot ;-)

My SelectRoom component (link) uses a simple SSE source, I see an error in the browsers developer console when a room is selected and the component is destroyed.

Should the SSE connection be removed manually in the client when a component is removed by using onDestroy()?

razshare commented 9 months ago

See Other notes.

The source() function, its select(), transform() and json() sub-functions, all return a Readable<T> store.\ Whenever the store loses all its subscribers, the stream is automatically disconnected.

Whenever you use the $ syntax to read from a store, svelte handles store unsubscribers for you automatically.

Which means that your SSE connection will automatically be closed when the component is destroyed (assuming the store is not being used somewhere else in the application).

You can observe this behavior in your network inspector.

Here's an example

<!-- src/lib/components/example.svelte -->
<script>
  import { source } from 'sveltekit-sse'
  const quotes = source('/events').select('thousands-of-cat-quotes').json()
</script>

<h3>Thousands of Cat Quotes</h3>
{#each $quotes ?? [] as quote}
  <span>{quote.value}</span><br />
{/each}
<!-- src/routes/+page.svelte -->
<script>
  import Example from '../components/example.svelte'
  let counter = 0
  function increaseCounter() {
    counter += 1
  }
</script>

<button on:click={increaseCounter}>
  <span>Reload all components</span>
</button>

{#key counter}
  <Example />
{/key}

This sample will make it so that whenever you click the Reload all components button, the Example component will be destroyed and recreated, thus disconnecting and reconnecting the stream source.

Peek 2024-01-27 04-53

You can also manually close it like this

image


By the way, I sent you a PR on that project of yours, fixing some things.

You can see the streams connecting and disconnecting in your chat room example as well Peek 2024-01-27 05-18

I see an error in the browsers developer console when a room is selected and the component is destroyed.

I'm not getting this error, I'm assuming it's because you were using event instead of events before, I haven't checked your original code.