当前位置:网站首页>Dart series: using generators in dart

Dart series: using generators in dart

2022-06-24 00:10:00 Procedural stuff

brief introduction

ES6 While introducing asynchronous programming , It has also been introduced. Generators, adopt yield Keywords to generate the corresponding data . alike dart Also have yield Keywords and generator concepts .

When is the generator ? The so-called generator is a device that can continuously generate some data , It's also called generator.

Two return types generator

It depends on whether it is generated synchronously or asynchronously ,dart The results returned are also different .

In case of synchronous return , So the return is a Iterable object .

If it's an asynchronous return , So the return is a Stream object .

synchronous generator Use sync* The key words are as follows :

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

Asynchronous generator It uses async* The key words are as follows :

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

Generate keywords using yield.

If yield Followed by itself is a generator, Then you need to use yield*.

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

Stream The operation of

stream Represents a stream , After getting this stream , We need to extract the corresponding data from the stream .

from Stream There are two ways to get data from , The first is to use Stream Of itself API To get Stream Data in .

The simplest is to call stream Of listen Method :

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

listen Processing methods that 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 onData Method .

The other is what we're going to talk about today await for.

await for The grammar is as follows :

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

Note that the above expression Must be a Stream object . also await for Must be used in async in , as follows :

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

If you want to interrupt stream Listening in , You can use break perhaps return.

summary

That's all dart The use of the generator in .

This article has been included in http://www.flydean.com/13-dart-generators/ The most popular interpretation , The deepest dry goods , The most concise tutorial , There are so many tricks you don't know about waiting for you to discover !

原网站

版权声明
本文为[Procedural stuff]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/11/20211123102403994W.html