Re: [whatwg/dom] Improving ergonomics of events with Observable (#544)

I'm not particularly convinced `ReadableStream` should be ruled out as a candidate for this. Modern web APIs have overwhemingly being using promises which don't support synchronous response at all.

> ReadableStream and AsyncIterator are implemented on top of promise, meaning that they're also tied to the same scheduling restrictions. Restrictions that make them not viable as an abstraction for eventing, as events can be subscribed to, dispatched and torn down synchronously.

Just to point out something, the only thing that can't be done synchronously is to receive a value. Streams (just like async functions) call basically everything synchronously, it's just that you can't receive the result until some future tick.

e.g.:
- `new ReadableStream({ start, pull, cancel })` calls `start` synchronously
- `reader.read()` calls `pull` synchronously (if needed)
- `stream.cancel()` calls `cancel` synchronously

The only real problem, and this is also shared by promises in general, is that if the promise is already resolved you can't abort it. Although as this is a problem for promises in general I don't think it's that great of an idea to create new primitives just to sidestep it in a few cases.

Obviously there's also the whole `.preventDefault`/`.stopPropagation` things that can't really be made asynchronous as-is, although it'd probably be worth investigating whether [this suggestion](https://github.com/whatwg/dom/issues/544#issuecomment-351744903) is workable, if not we could just tack on a synchronous step e.g.:

```js
const clickEvents = element.events("click", {
  // just a small sync handler for enabling .preventDefault/.stopPropagation
  syncHandler: (event) => { if (someCondition) event.preventDefault() },
});

for await (const event of clickEvents) {
  // Do the complicated work here
}
```

One particular advantage of using `ReadableStream` is that because it's specified to be async iterable, when proposals such as the [iterators helpers proposal](https://github.com/tc39/proposal-iterator-helpers) land any such methods will automatically be gained by the corresponding iterator for `ReadableStream` ([as per WebIDL](https://heycam.github.io/webidl/#es-asynchronous-iterator-prototype-object)).

-- 
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/whatwg/dom/issues/544#issuecomment-860149962

Received on Sunday, 13 June 2021 04:39:52 UTC