Home > OS >  How to optionally add timeout or onError on a Future chain?
How to optionally add timeout or onError on a Future chain?

Time:08-30

I have a function with following code:

Future wrap(Future future, Duration? timeoutDuration) {
    return future.timeout(timeoutDuration).onError(handleError);
}

In some cases, I want to be able to skip adding a timeout, for e.g. when timeoutDuration is null. So, it should just be:

return future.onError(handleError);

One way to do this is to use if condition on nullability of timeoutDuration. But, this gets complicated if (in future; no pun) I want to do the same for onError when handleError is null. Here's my attempt:

Future wrap(Future future, Duration? timeoutDuration) {
  return _optionalErrorHandler(
    _optionalTimeout(future, timeoutDuration),
    () {},
  );
}

Future _optionalTimeout(Future future, Duration? timeoutDuration) {
  if (timeoutDuration == null) {
    return future;
  }

  return future.timeout(timeoutDuration);
}

Future _optionalErrorHandler(Future future, Function()? handler) { // handler: just for example
  if (handler == null) {
    return future;
  }

  return future.onError((error, stackTrace) => handler());
}

I want to ask if this is an optimal or recommended way to do this? Is there any inbuilt API that allows me to do this conditionally?

CodePudding user response:

Seems like a good use case for extensions.

extension FutureExt<T> on Future<T> {
  Future<T> timeoutNullable(Duration? timeLimit, {FutureOr<T> onTimeout()?}) {
    if (timeLimit != null) {
      return timeout(timeLimit, onTimeout: onTimeout);
    } else {
      return this;
    }
  }
}
  • Related