相关疑难解决方法(0)

使用 Stream.periodic 时如何取消 Stream?

我在取消使用 Stream.periodic 构造函数创建的流时遇到问题。下面是我尝试取消流。但是,我很难从内部作用域中提取“计数”变量。因此,我无法取消订阅。

import 'dart:async';

void main() {
  int count = 0;
  final Stream newsStream = new Stream.periodic(Duration(seconds: 2), (_) {
    return _;
  });

  StreamSubscription mySubscribedStream = newsStream.map((e) {
    count = e;
    print(count);
    return 'stuff $e';
  }).listen((e) {
    print(e);
  });

  // count = 0 here because count is scoped inside mySubscribedStream
  // How do I extract out 'count', so I can cancel the stream?
  if (count > 5) {
    mySubscribedStream.cancel();
    mySubscribedStream = null;
  }
}
Run Code Online (Sandbox Code Playgroud)

dart

12
推荐指数
1
解决办法
4268
查看次数

标签 统计

dart ×1