loading...

re: Explain Futures and Streams in Dart like I'm Five VIEW POST

FULL DISCUSSION
 

This may have already been answered pretty well, and I'm not sure a 5 year old will get this, but I'd like to have a go with some code snippets.

So...

Futures are to Dart, what Promises are to JavaScript.

In other words, I give you my word that when the time is right, I will provide the full result.

In JavaScript, we would have something along the lines of:

const asyncRequest = () => new Promise(function(resolve, reject) {

  setTimeout(function() {
    resolve("Completed");
  }, 1000);

});

asyncRequest().then((result) => console.log(result));

And in Dart:

import 'dart:async';

asyncRequest() {
  var completer = new Completer();

  new Timer(new Duration(seconds: 1), () {
    completer.complete("Completed");
  });

  return completer.future;
}

void main() {
    asyncRequest().then((result) => print(result));
}

With streams however:

Streams are to Dart, what Events are to JavaScript.

For example, typing on the keyboard creates a stream/sequence of keypresses, which are processed using events

In JavaScript, we would have something along the lines of:

document.querySelector('#input')
    .addEventListener('keypress', (e) => console.log('Value changed.'));

And in Dart:

import 'dart:html';

void main() {
    querySelector('#input')
        .addEventListener('keypress', (e) => print("Value changed"));
}

with another whereby each letter is streamed as a sequence of single characters.

import 'dart:async';

void main() {
  List<String> alphabets = 'abcdefghijklmnopqrstuvwxyz'.split('');
  var stream = new Stream.fromIterable(alphabets);

  stream.listen((data) => print(data));
}

Hope this enlightens somehow.

 

Streams are to Dart, what Events are to JavaScript.

This!! This right here clarified the streams concept. Thanks.

In the case of streaming each key in the code sample, where would you generally use the stream? Since in this case I assume the split() is similar to the js one, so it'd do that synchronously. The example does clarify the concept, I'm just curious as to what use cases there would be

 

Hey @allanjeremy , this stream has several applications. For example on the UI you could be simulating a text typing effect. See this DartPad for example.

Hey Jermaine, thanks for sharing. Managed to wrap my head around the concept through all the great responses

Code of Conduct Report abuse