Closed bluepuma77 closed 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.
You can also manually close it like this
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
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.
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()
?