DEV Community


Discussion on: Explain Futures and Streams in Dart like I'm Five

stargator profile image


Futures are like Promises. In fact, when Dart compiles into JavaScript, Futures are replaced with Promises.

Streams are essentially a subscription event handler.

In AngularDart, I'll use a Stream in a component like this:

  Stream<bool> get onButtonClose =>;
  final StreamController<bool> _onButtonClose = new StreamController<bool>.broadcast();

And in the component's element I'll wrap an attribute of the same name as the variable tagged with the @Output annotation in parentheses:

<component (onButtonClose)="closeUI($event)"></component>

This means when the Stream has an event, it will trigger the closeUI() function and pass the event object as a parameter. Note: The Stream is set to pass objects of type bool (Stream<bool>), so the closeUI function must accept bool as a parameter.

That's the basics, but not for a five year old.

So let me go simpler:

A Future is something you can hold onto until the thing you actually want is available.

A Stream is a subscription, whenever something of interest is available, it will be passed through the Stream.

allanjeremy profile image
Allan N Jeremy Author

Great, thanks. Understood Futures from the promises example. I really didn't get streams until the last sentence.

Still trying to grasp how I'd use them based on your explanation. So do streams generally take futures as values? Or how exactly do they work?

Going by

whenever something of interest is available, it will be passed through the Stream.

Wouldn't a future just work equally as well? I may be a little confused here. I can see use cases for futures, but still confused on how or when I'd need a stream. Do you mind giving an example use-case in production?