Skip to content

Generators.observe needs a better way to throw? (And end?) #44

Open
@mbostock

Description

@mbostock

It’s possible if you notify with a rejected Promise, but this seems a little awkward. For example:

Generators.observe(notify => {
  const socket = new WebSocket("wss://ws.blockchain.info/inv");
  socket.onerror = () => notify(Promise.reject(new Error("socket error")));
  socket.onopen = () => socket.send(JSON.stringify({op: "unconfirmed_sub"}));
  socket.onmessage = event => notify(JSON.parse(event.data));
  return () => socket.close();
})

We could pass two callbacks, resolve and reject, instead (or next and error for symmetry with the Observable proposal; maybe it would be confusing to use the name resolve when it can be called repeatedly)?

Generators.observe((resolve, reject) => {
  const socket = new WebSocket("wss://ws.blockchain.info/inv");
  socket.onerror = () => reject(new Error("socket error"));
  socket.onopen = () => socket.send(JSON.stringify({op: "unconfirmed_sub"}));
  socket.onmessage = event => resolve(JSON.parse(event.data));
  return () => socket.close();
})

But even then we don’t have a way to indicate that the observable stream has ended (without an error). That would correspond to the observer.complete method. If we passed an observer in instead, that would look like:

Generators.observe(observer => {
  const socket = new WebSocket("wss://ws.blockchain.info/inv");
  socket.onerror = () => observer.error(new Error("socket error"));
  socket.onopen = () => socket.send(JSON.stringify({op: "unconfirmed_sub"}));
  socket.onmessage = event => observer.next(JSON.parse(event.data));
  return () => socket.close();
})

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions