语境
下面的代码代表一种抽象,其中MyClass
是某种下载管理器。
import 'dart:async';
Future<void> main() async {
MyClass().test().listen((v) => print('t1: $v')).onError(print);
final commomClass = MyClass();
commomClass.test().listen((v) => print('t2: $v')).onError(print);
commomClass.test().listen((v) => print('t3: $v')).onError(print);
}
class MyClass {
bool _isDownloadInProgress = false;
int _i = 0;
StreamController<int> _sc;
Stream<int> test() async* {
if (_isDownloadInProgress) {
throw Exception('Download already in progress');
} else {
_sc = StreamController<int>();
}
Timer.periodic(
const Duration(seconds: 1),
(t) {
if (_i == 4) {
_isDownloadInProgress = false;
_i = 0;
_sc.close();
t.cancel();
} else {
_sc.add(_i++);
}
},
);
yield* _sc.stream;
}
}
问题
我希望在执行此代码后,它会生成值 t1 和 t2,并且输出 t3 只会生成一次“正在下载”。例如:
t1: 0
t2: 0
t3: Download already in progress
t1: 1
t2: 1
t1: 2
t2: 2
t1: 3
t2: 3
但它会输出所有四个 t1
值、八个 t3
值,并且没有“正在下载”消息:
t1: 0
t3: 0
t3: 1
t1: 1
t3: 2
t3: 3
t1: 2
t3: 0
t1: 3
t3: 1
t3: 2
t3: 3
对我来说,这些t1
值会正确输出,t2
也会正确输出,并且t3
会输出“正在下载”消息,因为一切都是异步运行的,它会尝试“下载”已经下载的内容(因为该test()
方法是在MyClass
) 的同一个实例上调用的。
我错过了什么?