Defer
The defer is a small function intended to simplify the use of functions that require to execute postponed actions.
Version: 1.0.0
About this software
This is probably one of the smallest software in size.
Below is the source code of this library.
import 'dart:async';
/// Executes the function [action].\
/// After the [action] function is completed, executes the `postponed` function
/// [onExit].
Future<T> defer<T>(
Future<void> Function() onExit,
FutureOr<T> Function() action,
) async {
try {
return await action();
} finally {
await onExit();
}
}
Example
A small example of using the defer function:
import 'dart:async';
import 'package:defer/defer.dart';
import 'package:http/http.dart' as http;
Future<void> main() async {
final uri = Uri.parse('https://pub.dev/feed.atom1');
final bytes = <int>[];
final client = http.Client();
await defer(() async => client.close(), () async {
final request = http.Request('GET', uri);
final response = await client.send(request);
if (response.statusCode != 200) {
throw StateError('Http error (${response.statusCode}): $uri');
}
final iterator = StreamIterator(response.stream);
await defer(iterator.cancel, () async {
while (await iterator.moveNext()) {
bytes.addAll(iterator.current);
}
});
});
final text = String.fromCharCodes(bytes);
print(text);
}
Another example:
import 'package:defer/defer.dart';
import 'package:multitasking/synchronization/binary_semaphore.dart';
void main(List<String> args) async {
final lock = BinarySemaphore();
final fs = <Future<void>>[];
var n = 0;
for (var i = 0; i < 3; i++) {
fs.add(Future(() async {
await defer(lock.release, () async {
await lock.acquire();
n++;
print('n: $n');
// Allow other tasks to do their job.
await Future<void>.delayed(Duration(seconds: 1));
print('n: $n');
});
}));
}
await Future.wait(fs);
}
Results of work:
n: 1
n: 1
n: 2
n: 2
n: 3
n: 3