3

A dart:html.WebSocket opens once and closes once. So I'd expect that the onOpen and onClose properties would be Futures, but in reality they are Streams.

Of course, I can use stream.onClose.first to get a Future. But the done property on the dart:io version of WebSocket is a Future as expected, so I'm wondering if I'm missing something.

Why use Streams and not Futures in dart:html?

hopper
  • 13,060
  • 7
  • 49
  • 53
StephanS
  • 843
  • 1
  • 8
  • 20
  • Just a guess, but perhaps they can send multiple errors, a Future can only provide one error. – Greg Lowe Feb 09 '15 at 21:32
  • Maybe because they are events in JavaScript DOM were something like a one shot event doesn't exist (now we have Promises/Futures in JS, too!). The Dart code is generated from the DOM definiton and all events are translated into streams. – Fox32 Feb 09 '15 at 21:50

1 Answers1

4

In a word: transparency. The purpose of the dart:html package is to provide access to the DOM of the page, and so it mirrors the underlying DOM constructs as closely as possible. This is in contrast with dart:io where the goal is to provide a convenient server-side API rather than exposing some underlying layer.

Sure, as a consumer of the API you would expect open and close to be fired only once, whereas message would be fired multiple times, but at the root of things, open, close, message, and error are all just events. And in dart:html, DOM events are modeled as streams.

And actually, a WebSocket could very well fire multiple open events (or close events). The following is definitely a contrived example, but consider this snippet of javascript:

var socket = new WebSocket('ws://mysite.com');
socket.dispatchEvent(new Event('open'));
socket.dispatchEvent(new Event('open'));
socket.dispatchEvent(new Event('open'));

How would a Dart WebSocket object behave in a situation like this, if onOpen were a Future rather than a Stream? Of course I highly, highly doubt this would ever surface out there in the "real world". But the DOM allows for it, and dart:html should not be making judgment calls trying to determine which situations are likely and which are not. If it's possible according to the spec, dart:html should reflect that. Its role is simply to pass through the behavior - as transparently as possible - and let the consumer of the API decide what cases they need to handle and which they can ignore.

hopper
  • 13,060
  • 7
  • 49
  • 53