event-iterator icon indicating copy to clipboard operation
event-iterator copied to clipboard

What is the reason why you need to use `.call()` and `.apply()` on `subscribe` and/or `stream`?

Open EloB opened this issue 5 years ago • 2 comments

I just found this library and thought it looked cool and saw that you need either call or apply on subscribe and stream. What is the reason behind that?

EloB avatar Oct 25 '20 17:10 EloB

Yea, what gives?

I was thinking of how i could do this myself. I wanted to turn WebSocket's onMessage event and turn it into a async iterator

I first thought about a own solution before looking into how others have solved it before bringing in any other dependency. to compare my solution to any lib/tool/util fns

my gut says that you don't really need any fancy tools to help out with this, it seems easy do make it yourself with just a few line of codes

async function* onclick() {
  while (true) 
  yield await new Promise(rs => window.onclick = rs)
}

for await (let evt of onclick())
  console.log(evt)

sure it dose not have any cancelation or using any addEventListener. but if you build things yourself you get more customizable behavior and don't have to learn a new tools

Need cancelation? sure, you can use AbortController for that with EventTargets newly added signal option. This can give you one way to stop a lot of things at once if you eg leave a SPA for next page this can work in Node also, they have added EventTarget and AbortController to the core - in a hope to one day maybe implement fetch on the server, but also for other stuff

async function* onclick(signal) {
  while (true) 
  yield await new Promise(rs => window.addEventListener('click', rs, { once: true, signal })
}

const abortController = new AbortController()

// later abortController.abort()

for await (let evt of onclick(signal))
  console.log(evt)

Not as much different from how you would write it yourself and if you used a tool, sure your's cover more bases

jimmywarting avatar Feb 09 '21 16:02 jimmywarting

I just found this library and thought it looked cool and saw that you need either call or apply on subscribe and stream. What is the reason behind that?

The reason was that it was pretty easy to use with the proposed bind operator. But that never really took off.

rolftimmermans avatar Feb 09 '21 16:02 rolftimmermans