如何在Stream.periodic中调用异步函数

时间:2019-08-19 15:32:14

标签: flutter dart

是否可以在dart:Stream.periodic函数内调用异步函数?

我尝试包装异步函数,但是它不起作用,请参见下面的代码。

update

2 个答案:

答案 0 :(得分:0)

我对dart流还不太熟悉,但是您应该能够像这样模拟您要实现的目标:

final controller = StreamController<String>();

Timer timer;
controller.onListen = () {
  timer = Timer.periodic(
    _pollingInterval,
    (timer) => _connectionRepository.checkConnection().then((data){ 
       if(!controller.isClosed){
         controller.add(data);
       }
    }),
  );
};
controller.onCancel = () {
  timer?.cancel();
}

return controller.stream;

该流不支持暂停和继续。如果需要的话,您需要覆盖控制器上的相应回调并在那里启动/停止计时器。

此外,根据checkConnection的时间,这可能导致流中的事件与_pollingInterval完全不同。

答案 1 :(得分:0)

使用asyncMap:

var button = UIButton()

newGameButton.setTitle("Новая игра", for: .normal)
newGameButton.setImage(UIImage(named: "energi"), for: .normal)
newGameButton.backgroundColor = .blue
newGameButton.imageEdgeInsets.left = -50
相关问题