razshare / sveltekit-sse

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

`emit` not working more than once #40

Closed BearToCode closed 6 months ago

BearToCode commented 6 months ago

I've just copied the example:

export function POST({ request }) {
  return events({
    request,
    async start({emit}) {
      while(true){
        emit('message', 'hello world')
        await delay(1000)
      }
    },
  })
}

And did the following on the client:

<script>
  const value = source('/sse/chat').select('message');

  value.subscribe((message) => {
    console.log(message);
  });
</script>

But 'hello world' is being logged only once! example

razshare commented 6 months ago

Hello @BearToCode ,

The emit function is working correctly in this case.

The behavior you're experiencing is the default behavior of svelte's stores. A svelte store does not forward duplicate values, it checks for equality. If value N+1 is equal to value N, then the value of the store won't change, thus your subscribe function won't trigger.

That's just how svelte stores work. See reference here.

This library does provide a solution. What you're looking for is transform()

<script>
  const value = source('/sse/chat').select('message').transform((message) => {
    console.log(message);
    return message
  });
</script>

Make sure you update to the latest 0.12.1 version to get this feature working properly.


I agree the readme is a bit confusing since it's emitting a static string, so I've updated it to emit a variable string.

Let me know if this addresses your issue.

BearToCode commented 6 months ago

My bad, now it's working. Grazie mille :)