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

Flutter 如何在Stream.periodic中调用异步函数,flutter,dart,Flutter,Dart,是否可以在dart:Stream.periodic函数中调用异步函数 我试图包装我的异步函数,但它不工作,请参阅下面的代码 Stream.periodic(持续时间(秒):\u pollingInterval),\u检查连通性) 字符串检查连接(int x)异步{ 返回wait_connectionRepository.checkConnection(); } 我还不太熟悉dart流,但您应该能够模拟您试图实现的目标,如下所示: final controller=StreamController

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

我试图包装我的异步函数,但它不工作,请参阅下面的代码

Stream.periodic(持续时间(秒):\u pollingInterval),\u检查连通性)
字符串检查连接(int x)异步{
返回wait_connectionRepository.checkConnection();
}

我还不太熟悉dart流,但您应该能够模拟您试图实现的目标,如下所示:

final controller=StreamController();
定时器;
controller.onListen=(){
定时器=定时器。周期性(
_污染间期,
(计时器)=>\u connectionRepository.checkConnection()。然后((数据){
如果(!controller.isClosed){
控制器。添加(数据);
}
}),
);
};
controller.onCancel=(){
计时器?.cancel();
}
返回控制器.stream;
但是,流不支持暂停并继续。如果需要,您需要覆盖控制器上相应的回调,并在那里启动/停止计时器

此外,根据
checkConnection
的计时,这可能会导致流中的事件与
\u pollingInterval
使用异步映射非常不同:

Stream checkConnectionStream()异步*{
产量*流周期性(持续时间(秒:_pollingInterval),(u){
返回wait_connectionRepository.checkConnection();
}).asyncMap((事件)async=>wait事件);
}

您不能在流中调用异步函数,让该函数返回未来并保持非异步。在流链的下一部分使用未来。你能提供一个示例代码吗?