|
|
@@ -1,7 +1,5 @@
|
|
|
import 'dart:async';
|
|
|
|
|
|
-import 'package:flutter/widgets.dart';
|
|
|
-
|
|
|
import 'async_typeof.dart';
|
|
|
import 'cancel_future.dart';
|
|
|
|
|
|
@@ -105,37 +103,34 @@ class AsyncUtil {
|
|
|
});
|
|
|
}
|
|
|
|
|
|
- ///实际delay第一次执行的时间为delay+interval
|
|
|
- static CancelableFuture<T> interval<T>(FutureCallback<T> callback,
|
|
|
- Duration delay, Duration interval, int times) {
|
|
|
+ static StreamController<T> interval<T>(
|
|
|
+ IntervalCallback<T> callback, Duration interval, int times,
|
|
|
+ {Duration? delay}) {
|
|
|
Timer? timer;
|
|
|
- Timer? delayTimer;
|
|
|
- int counter = 0;
|
|
|
-
|
|
|
- void tick(Completer<T> completer) {
|
|
|
- if (counter < times) {
|
|
|
- callback().then((value) {
|
|
|
- if (!completer.isCompleted) {
|
|
|
- completer.complete(value);
|
|
|
- }
|
|
|
- }).catchError((error) {
|
|
|
- if (!completer.isCompleted) {
|
|
|
- completer.completeError(error);
|
|
|
- }
|
|
|
- });
|
|
|
- counter++;
|
|
|
- } else {
|
|
|
- timer?.cancel();
|
|
|
- }
|
|
|
- }
|
|
|
-
|
|
|
- return CancelableFuture<T>((completer) {
|
|
|
- delayTimer = Timer(delay, () {
|
|
|
- timer = Timer.periodic(interval, (Timer t) => tick(completer));
|
|
|
- });
|
|
|
- }, () {
|
|
|
- delayTimer?.cancel();
|
|
|
+ StreamController<T> controller = StreamController<T>(onCancel: () {
|
|
|
timer?.cancel();
|
|
|
});
|
|
|
+ int count = 0;
|
|
|
+ void tick() {
|
|
|
+ callback(count).then((value) {
|
|
|
+ controller.add(value);
|
|
|
+ count++;
|
|
|
+ if (count < times) {
|
|
|
+ timer = Timer(interval, tick);
|
|
|
+ } else {
|
|
|
+ controller.close();
|
|
|
+ }
|
|
|
+ }).catchError((error) {
|
|
|
+ controller.addError(error);
|
|
|
+ controller.close();
|
|
|
+ });
|
|
|
+ }
|
|
|
+
|
|
|
+ if (delay != null && delay > Duration.zero) {
|
|
|
+ timer = Timer(delay, tick);
|
|
|
+ } else {
|
|
|
+ tick();
|
|
|
+ }
|
|
|
+ return controller;
|
|
|
}
|
|
|
}
|