2.4、Dart语言基础:异步

2021-12-16  本文已影响0人  双鱼子曰1987

学习笔记,旨在于快速入门和学习Dart,其中可能会有理解错误,请指出,一起学习。

系列文章

2.1、Dart语言基础:变量、运算符
2.2、Dart语言基础:函数与闭包
2.3、Dart语言基础:面向对象
2.4、Dart语言基础:异步
2.5、Dart语言基础:库与包
...

一、概述

1、异步使用常见

2、Dart语言中,异步相关的两个对象Future or Stream

Dart libraries are full of functions that return Future or Stream objects.

3、使用异步的两种方式

4、导入头文件import 'dart:async';


二、Future

1、常用接口

.then 状态完成后回调
.delayed 延迟多少秒后,执行回调
.whenComplete 无论成功和失败都会执行
.catchError 发生错误,必须在then之后

  Future.delayed(Duration(seconds: 3), (){
    return 'Async: hello';
  }).then((value) => {
    print('then: recv ${value}')
  }).catchError((e){
    print('err: $e');
  }).whenComplete(() => {
    print('finish!')
  });

// 打印
// then: recv Async: hello
// finish!
  Future.wait([
    Future.delayed(Duration(seconds: 3), (){
      return 'Hello';
    }),
    Future.delayed(Duration(seconds: 6), (){
      return ' World';
    })
  ]).then((value) => {
    print('Recv: $value')
  });

// 打印
// Recv: [Hello,  World]

2、多个Future对象

  Future result = costlyQuery(url);
  result.then((value) => expensiveWork(value))
  .then((_) => lengthyComputation())
  .then((_) => print('Done!'))
  .catchError((exception) {
    /* Handle exception... */
  }); 

// 等价于
try {
  final value = await costlyQuery(url);
  await expensiveWork(value);
  await lengthyComputation();
  print('Done!');
} catch (e) {
  /* Handle exception... */
}
Future<void> deleteLotsOfFiles() async =>  ...
Future<void> copyLotsOfFiles() async =>  ...
Future<void> checksumLotsOfOtherFiles() async =>  ...

await Future.wait([
  deleteLotsOfFiles(),
  copyLotsOfFiles(),
  checksumLotsOfOtherFiles(),
]);
print('Done with all the long steps!');

三、Stream

1、在循环中使用异步Using an asynchronous for loop

void main(List<String> arguments) {
  // ...
  FileSystemEntity.isDirectory(searchPath).then((isDir) {
    if (isDir) {
      final startingDir = Directory(searchPath);
      startingDir.list().listen((entity) {
        if (entity is File) {
          searchFile(entity, searchTerms);
        }
      });
    } else {
      searchFile(File(searchPath), searchTerms);
    }
  });
}

// 等价于
Future<void> main(List<String> arguments) async {
  // ...
  if (await FileSystemEntity.isDirectory(searchPath)) {
    final startingDir = Directory(searchPath);
    await for (final entity in startingDir.list()) {
      if (entity is File) {
        searchFile(entity, searchTerms);
      }
    }
  } else {
    searchFile(File(searchPath), searchTerms);
  }
}

2、常用接口

监听流的数据或事件

submitButton.onClick.listen((e) {
  // When the button is clicked, it runs this code.
  submitData();
});
first()
last()
single()
// 单个数据前的拦截测试
firstWhere()
lastWhere()
singleWhere()
skip()
skipWhile()
take()
takeWhile()
where()

流数据转换(Transforming stream data)

var lines = inputStream
    .transform(utf8.decoder)
    .transform(const LineSplitter());

完成状态

3、Stream 和 Future 的区别点

  Stream.fromFutures([
    Future.delayed(Duration(seconds: 1), (){
      return 'result 1';
    }),
    Future.delayed(Duration(seconds: 2), (){
      throw AssertionError('sorry!');
    }),
    Future.delayed(Duration(seconds: 3), (){
      return 'result 2';
    })
  ]).listen((event) {
    print('listen: $event');
  }, onError: (e){
    print('err: $e');
  }, onDone: (){
    print('finish!');
  });

// 打印
listen: result 1
err: Assertion failed: "sorry!"
listen: result 2
finish!

四、async、await/await-for

// 倒计时
void countSeconds(int s) {
  for (var i = 1; i <= s; i++) {
    Future.delayed(Duration(seconds: i), () => print(i));
  }
}

// 延迟例子
Future<void> printOrderMessage() async {
  print('Awaiting user order...');
  var order = await fetchUserOrder();
  print('Your order is: $order');
}

Future<String> fetchUserOrder() {
  return Future.delayed(const Duration(seconds: 4), () => 'Large Latte');
}

Future<void> main() async {
  countSeconds(4);
  await printOrderMessage();
}

// 输出
Awaiting user order...
1
2
3
4
Your order is: Large Latte

1、await --> Future

String lookUpVersion() {
  return '0.0.1';
}

Future<void> checkVersion() async {
  var version = await lookUpVersion();
  print(version);
}

2、await for --> Stream

await for (varOrType identifier in expression) {
  // Executes each time the stream emits a value.
}
Future<void> main() async {
  await for (final request in requestServer) {
    handleRequest(request);
  }
}

3、捕获async的异常。

try {
  print('Awaiting ...');
} catch (err) {
  print('Caught error: $err');
}
参考

in the library tour

上一篇 下一篇

猜你喜欢

热点阅读