flutter【10】dart语言--异步支持

异步支持

dart 中包含很多返回 Future 和 Stream 对象的方法,这些方法都是一步的,比如 I/O。

async 和 await 关键字支持异步编程。

处理 Futures

  • 使用 async 和 await
  • 使用 Future API,参考Future
//使用 async 修饰方法,使用 await 调用方法
Future checkVersion() async {
  var version = await lookUpVersion();
  // Do something with version
}

await lookUpVersion();

要使用 await,其方法必须带有 async 关键字,async 方法只会在遇到第一个 await 表达式时才会执行。

可以使用 try, catch, 和 finally 来处理使用 await 的异常。

try {
  server = await HttpServer.bind(InternetAddress.LOOPBACK_IP_V4, 4044);
} catch (e) {
  // React to inability to bind to the port...
}

可以对一个 async 方法多次使用 await 。

var entrypoint = await findEntrypoint();
var exitCode = await runExecutable(entrypoint, args);
await flushThenExit(exitCode);

await 表达的返回值通常时 Future ,如果不是,则会自动包装成一个 Futre。 Future 表示承诺返回一个对象,await 表达式会让程序暂停,知道该对象可用。

声明异步方法

一个 async 方法是函数体被标记为 async 的方法。

//同步方法
String lookUpVersion() => '1.0.0';

//异步方法
Future<String> lookUpVersion() async => '1.0.0';

异步方法会返回一个 Future,定义异步方法时不需要使用 Future API,dart会自动创建 Future 对象。

如果异步方法没有返回值,则需要明确标记返回类型为 Future<void>

处理 Stream

  • 使用 async 和 异步循环 await for
  • 使用 Stream API,参考Stream

注意:使用 await for 时,要确实需要处理streams的所有结果。例如像UI事件监听就不需要使用asait for ,因为UI框架会发送无用的streams。

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

expression 必须返回 Stream 类型

  1. 等待,直到 stream 发射一个值
  2. 使用发射的值,执行循环
  3. 重复1,2,直到stream关闭

停止监听一个stream,可以使用 break 或者 return 语句。

async for 确保在 async 方法中使用。

main() async {
  ...
  await for (var request in requestServer) {
    handleRequest(request);
  }
  ...
}

猜你喜欢

转载自blog.csdn.net/weixin_34161083/article/details/87381416