add<T> method
将一个异步任务加入串行队列执行。
tag用于标记任务,进入 waitingList;用于调试与可视化。- 串行语义:后加入的任务会等待之前任务完成后再执行。
Implementation
Future<T> add<T>(String tag, Future<T> Function() task) {
final inflight = _inflightByTag[tag];
if (inflight != null) {
return inflight as Future<T>;
}
waitingList.add(tag);
final completer = Completer<T>();
_inflightByTag[tag] = completer.future;
_tail = _tail.then((_) async {
// 如果外部提前 remove 了(一般不建议),则跳过执行。
if (!waitingList.contains(tag)) {
if (!completer.isCompleted) {
completer.completeError(StateError('Permission task removed: $tag'));
}
return;
}
try {
final result = await task();
if (!completer.isCompleted) {
completer.complete(result);
}
} catch (e, st) {
if (!completer.isCompleted) {
completer.completeError(e, st);
}
} finally {
remove(tag);
_inflightByTag.remove(tag);
}
});
return completer.future;
}