Introduction

While asynchronous programming is introduced in ES6, Generators are also introduced to generate corresponding data through the yield keyword. The same dart also has the concept of yield keywords and generators.

When is the generator? The so-called generator is a device that can continuously produce certain data, also called generator.

Generator with two return types

Depending on whether it is generated synchronously or asynchronously, the results returned by dart are also different.

If it is a synchronous return, then an Iterable object is returned.

If it is returned asynchronously, then a Stream object is returned.

Synchronous generators use sync* keywords as follows:

Iterable<int> naturalsTo(int n) sync* {
  int k = 0;
  while (k < n) yield k++;
}

The asynchronous generator uses async* keywords as follows:

Stream<int> asynchronousNaturalsTo(int n) async* {
  int k = 0;
  while (k < n) yield k++;
}

Use yield to generate keywords.

If the yield followed by itself is a generator, you need to use yield*.

Iterable<int> naturalsDownFrom(int n) sync* {
  if (n > 0) {
    yield n;
    yield* naturalsDownFrom(n - 1);
  }
}

Stream operation

Stream represents a stream. After getting this stream, we need to take out the corresponding data from the stream.

There are two ways to retrieve data from the Stream. The first is to use the API of the Stream itself to obtain the data in the Stream.

The simplest is to call the listen method of stream:

  StreamSubscription<T> listen(void onData(T event)?,
      {Function? onError, void onDone()?, bool? cancelOnError});

The processing method that listen can receive data, the specific use is as follows:

 final startingDir = Directory(searchPath);
      startingDir.list().listen((entity) {
        if (entity is File) {
          searchFile(entity, searchTerms);
        }
      });

The default method is the onData method.

The other is the await for that I will explain today.

The syntax of await for is as follows:

await for (varOrType identifier in expression) {
  // Executes each time the stream emits a value.
}

It should be noted that the above expression must be a Stream object. And await for must be used in async, as follows:

Future<void> main() async {
  // ...
  await for (final request in requestServer) {
    handleRequest(request);
  }
  // ...
}

If you want to interrupt the monitoring of the stream, you can use break or return.

Summarize

The above is the use of generators in dart.

This article has been included in http://www.flydean.com/13-dart-generators/

The most popular interpretation, the most profound dry goods, the most concise tutorial, and many tips you don't know are waiting for you to discover!

Welcome to pay attention to my official account: "Program those things", know technology, know you better!


flydean
890 声望432 粉丝

欢迎访问我的个人网站:www.flydean.com