如何在Dart / Flutter中重试Future?

时间:2019-05-27 15:24:14

标签: flutter dart

我有一个方法可以进行一些异步处理,并希望它重试X次。如何在Dart / Flutter中实现?

3 个答案:

答案 0 :(得分:1)

使用此功能:

typedef Future<T> FutureGenerator<T>();
Future<T> retry<T>(int retries, FutureGenerator aFuture) async {
  try {
    return await aFuture();
  } catch (e) {
    if (retries > 1) {
      return retry(retries - 1, aFuture);
    }

    rethrow;
  }
}

并使用它:

main(List<String> arguments) {

  retry(2, doSometing);

}

Future doSometing() async {
  print("Doing something...");
  await Future.delayed(Duration(milliseconds: 500));
  return "Something";
}

答案 1 :(得分:0)

这是我的实现方式:

Future retry<T>(
    {Future<T> Function() function,
    int numberOfRetries = 3,
    Duration delayToRetry = const Duration(milliseconds: 500),
    String message = ''}) async {
  int retry = numberOfRetries;
  List<Exception> exceptions = [];

  while (retry-- > 0) {
    try {
      return await function();
    } catch (e) {
      exceptions.add(e);
    }
    if (message != null) print('$message:  retry - ${numberOfRetries - retry}');
    await Future.delayed(delayToRetry);
  }

  AggregatedException exception = AggregatedException(message, exceptions);
  throw exception;
}

class AggregatedException implements Exception {
  final String message;
  AggregatedException(this.message, this.exceptions)
      : lastException = exceptions.last,
        numberOfExceptions = exceptions.length;

  final List<Exception> exceptions;
  final Exception lastException;
  final int numberOfExceptions;

  String toString() {
    String result = '';
    exceptions.forEach((e) => result += e.toString() + '\\');
    return result;
  }
}

这是我的用法:

  try {
      await retry(
          function: () async {
            _connection = await BluetoothConnection.toAddress(device.address);
          },
          message: 'Bluetooth Connect');
    } catch (e) {
      _log.finest('Bluetooth init failed  ${e.toString()}');
    }

答案 2 :(得分:0)

我为Daniel Oliveira的回答添加了一个可选的延迟:

typedef Future<T> FutureGenerator<T>();
Future<T> retry<T>(int retries, FutureGenerator aFuture, {Duration delay}) async {
  try {
    return await aFuture();
  } catch (e) {
    if (retries > 1) {
      if (delay != null) {
        await Future.delayed(delay);
      }
      return retry(retries - 1, aFuture);
    }
    rethrow;
  }
}

您可以按以下方式使用它:

retry(2, doSometing, delay: const Duration(seconds: 1));