资料

Flutter异步编程-Future

事件循环EventLoop

  • Event Queue 主要包含IO、手势、绘制、定时器(Timer)、Stream流以及本文所讲Future等
  • MicroTask Queue 主要包含Dart内部的微任务(内部非常短暂操作),一般是通过 scheduleMicroTask 方法实现调度,它的优先级比Event Queue要高

事件循环执行的流程

在这里插入图片描述

Future的几种情况

1. factory Future(FutureOr computation())

//Future的factory构造函数
factory Future(FutureOr<T> computation()) {
  _Future<T> result = new _Future<T>();
  Timer.run(() {//内部创建了一个Timer
    try {
      result._complete(computation());
    } catch (e, s) {
      _completeWithErrorCallback(result, e, s);
    }
  });
  return result;
}

void main() {
  print('main is executed start');
  var function = () {
    print('future is executed');
  };
  Future(function);
  print('main is executed end');
}
//或者直接传入一个匿名函数
void main() {
  print('main is executed start');
  var future = Future(() {
    print('future is executed');
  });
  print('main is executed end');
}

2. Future.value()

main(List<String> args) {
  var commonFuture = Future(() {
    print('future is executed');
  });
  var valueFuture = Future.value(100.0);
  valueFuture.then((value) => print(value));
  print(valueFuture is Future<double>);
}
true
100.0
future is executed

3. Future.delayed()

main(List<String> args) {
  print('main start');
  var furtureList = Future.forEach([1, 2, 3, 4, 5, 6], (int element) {
    return Future.delayed(
        Duration(seconds: element), () => print('this is $element'));
  });
  print('main end');
}

Future的进阶使用

1. Future的forEach方法

main(List<String> args) {
  print('main start');
  var furtureList = Future.forEach([1, 2, 3, 4, 5, 6], (int element) {
    return Future.delayed(
        Duration(seconds: element), () => print('this is $element'));
  });
  print('main end');
}
main start
main end
this is 1
this is 2
this is 3
this is 4
this is 5
this is 6

2. Future的any方法

main(List<String> args) {
  print('main start');
  var futureList = Future.any([
    3,
    4,
    1,
    2,
    5
  ].map((delay) => Future.delayed(Duration(seconds: delay), () => delay)))
      .then(print)
      .catchError(print);
  print('main end');
}
main start
main end
1

3. Future的doWhile方法

main(List<String> args) {
  var totalDelay = 0;
  var delay = 0;

  Future.doWhile(() {
    if (totalDelay > 10) {
      // 超过10s跳出循环
      print('total delay: $totalDelay s');
      return false;
    }
    delay += 1;
    totalDelay = totalDelay + delay;
    return Future.delayed(Duration(seconds: delay), () {
      print('wait $delay s');
      return true;
    });
  });
}
wait 1 s
wait 2 s
wait 3 s
wait 4 s
wait 5 s
total delay: 15 s

4. Future的wait方法

main(List<String> args) {
  var requestApi1 = Future.delayed(Duration(seconds: 1), () => 15650);
  var requestApi2 = Future.delayed(Duration(seconds: 2), () => 2340);
  var requestApi3 = Future.delayed(Duration(seconds: 1), () => 130);

  Future.wait({requestApi1, requestApi2, requestApi3}).then((value) {
    // 最后将拿到的结果累加求和
    print('${value.reduce((value, element) => value + element)}');
  });
}
18120

5. Future的microtask方法

main(List<String> args) {
  var commonFuture = Future(() {
    print('common future is executed.');
  });
  var microtaskFuture =
      Future.microtask(() => print('microtask future is executed'));
}
microtask future is executed
common future is executed.

6. Future的sync方法

main(List<String> args) {
  print('main start');
  Future.sync(() => print('sync is executed!'));
  print('main is executed!');
}
main start
sync is executed!
main is executed!

处理Future返回的结果

1. Future.then方法

main(List<String> args) {
  // 普通Flutter会加入到MicroTask
  Future.delayed(Duration(seconds: 1), () => print('this is delayed future'));
  Future.sync(() => 100).then(print); // sync的Future需要加入到microtask Queue中
  print('main is executed!');
}
main is executed!
100
this is delayed future
main(List<String> args) {
  Future.delayed(Duration(seconds: 1), () => 100)
      .then((value) => Future.delayed(Duration(seconds: 1), () => 100 + value))
      .then((value) => Future.delayed(Duration(seconds: 1), () => 100 + value))
      .then((value) => Future.delayed(Duration(seconds: 1), () => 100 + value))
      .then(print); // 最后输出累加结果就是400
}
400

2. Future.catchError方法

main(List<String> args) {
  Future.delayed(Duration(seconds: 1), () => throw Exception('this is custom error!'))
      .catchError(print); // catchError回调返回异常的Future
}
Exception: this is custom error!
Unhandled exception:
type 'Null' is not a subtype of type 'Future<Never>'
#0      _FutureListener.handleError (dart:async/future_impl.dart:169:20)
#1      Future._propagateToListeners.handleError (dart:async/future_impl.dart:716:47)
#2      Future._propagateToListeners (dart:async/future_impl.dart:737:24)
#3      Future._completeError (dart:async/future_impl.dart:547:5)
#4      _completeWithErrorCallback (dart:async/future.dart:972:10)
#5      new Future.delayed.<anonymous closure> (dart:async/future.dart:317:11)
#6      Timer._createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:18:15)
#7      _Timer._runTimers (dart:isolate-patch/timer_impl.dart:395:19)
#8      _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:426:5)
#9      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:184:12)

3. Future.whenComplete方法

main(List<String> args) {
  Future.value(100)
      .then((value) => print(value))
      .whenComplete(() => print('future is completed!'));
  print('main is executed!');
}
main is executed!
100
future is completed!

main(List<String> args) {
  Future.delayed(
          Duration(seconds: 1), () => throw Exception('this is custom error'))
      .catchError(print)
      .whenComplete(() => print('future is completed!'));
  print('main is executed!');
}

main is executed!
Exception: this is custom error
future is completed!
Unhandled exception:
type 'Null' is not a subtype of type 'Future<Never>'
#0      _FutureListener.handleError (dart:async/future_impl.dart:169:20)
#1      Future._propagateToListeners.handleError (dart:async/future_impl.dart:716:47)
#2      Future._propagateToListeners (dart:async/future_impl.dart:737:24)
#3      Future._completeError (dart:async/future_impl.dart:547:5)
#4      _completeWithErrorCallback (dart:async/future.dart:972:10)
#5      new Future.delayed.<anonymous closure> (dart:async/future.dart:317:11)
#6      Timer._createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:18:15)
#7      _Timer._runTimers (dart:isolate-patch/timer_impl.dart:395:19)
#8      _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:426:5)
#9      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:184:12)
Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐