Why are onOpen and onClose Streams (not Futures) in dart:html WebSockets?

Issue

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?

Solution

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.

Answered By – hopper

Answer Checked By – Gilberto Lyons (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *