async icon indicating copy to clipboard operation
async copied to clipboard

Feature request: timeoutToNull extension method

Open jathak opened this issue 4 years ago • 2 comments

It would be useful to have a method on a Future<T> that returns a Future<T?> that resolves to null if it doesn't complete within a timeout.

This would be useful for cases like _exitCodeOrNull in test_process, which looked like this prior to null safety:

Future<int> get _exitCodeOrNull async =>
    await exitCode.timeout(Duration.zero, onTimeout: () => null);

but requires this when migrating to null safety, as exitCode is a Future<int> but we need a Future<int?>:

Future<int?> get _exitCodeOrNull => exitCode
    .then<int?>((value) => value)
    .timeout(Duration.zero, onTimeout: () => null);

With an extension method, this could be simplified to:

Future<int?> get _exitCodeOrNull => exitCode.timeoutToNull(Duration.zero);

cc: @nex3

jathak avatar Dec 09 '20 23:12 jathak

Note that this is in the same tradition as the collection package's firstWhereOrNull() et al extension methods.

nex3 avatar Dec 09 '20 23:12 nex3

It does make sense, yes.

lrhn avatar May 12 '21 08:05 lrhn