WICG / observable

Observable API proposal
https://wicg.github.io/observable/
Other
575 stars 14 forks source link

Alternative cancellation? #70

Closed benlesh closed 10 months ago

benlesh commented 1 year ago

One thing that is true about Observable is it's possible for an observable to cancel an observable.

It's worth proposing that at no extra cost, you can get any event fired to cancel if you have observable in your eco system.

Consider the following:

const closeSocket = document.querySelector('#close-socket');
const socket = new WebSocket(url);

const ac = new AbortController();
closeSocket.on('click').take(1).forEach(() => {
  ac.abort();
})

socket.on('open')
 .flatMap(() => socket.on('message'))
 .map(e => JSON.parse(e.data))
 .subscribe({
   next: console.log,
   signal: ac.signal,
 });

This could just as easily be:

const closeSocket = document.querySelector('#close-socket');
const socket = new WebSocket(url);

socket.on('open')
 .flatMap(() => socket.on('message'))
 .map(e => JSON.parse(e.data))
 .takeUntil(closeSocket.on('click'))
 .subscribe({
   next: console.log,
 })

Or even this:

const closeSocket = document.querySelector('#close-socket');
const socket = new WebSocket(url);

socket.on('open')
 .flatMap(() => socket.on('message'))
 .map(e => JSON.parse(e.data))
 .subscribe({
   next: console.log,
   signal: closeSocket.on('click')
 })

It's also arguable that AbortSignal itself could be "subscribable" given that it only has one event.

esprehn commented 1 year ago

I'm confused by these examples, why would you want to wait for open before listening for message on a WebSocket? You can just listen for message immediately, it'll never be dispatched until open happens.

The example also doesn't actually close the socket, it just closes the listener for the message events and then you're waiting for the GC to run and actually close the socket?

benlesh commented 10 months ago

I think I'm okay with what we've landed on.