dart - Dart Async 不等待完成
问题描述
我目前正在尝试等待 BLE 连接导致以下两种结果之一:
- 设备连接成功,或
- 扫描超时后设备连接失败
不是根据需要返回 true 或 false 值,而是立即返回 null,而无需等待函数完成。
我正在使用 dart 的 Future 和 async 功能来等待连接功能的完成。下面是我的代码:
BLE连接方法:
static Future<bool> connect(BluetoothDevice d) async {
// Connect to device
Duration timeout = new Duration(seconds: 5);
deviceConnection = _flutterBlue.connect(d, timeout: timeout).listen((s) {
deviceState = s;
if (s == BluetoothDeviceState.connected) {
device = d;
device.discoverServices().then((s) {
... Some service discovery stuff ...
});
}
}, onDone: () {
return deviceState == BluetoothDeviceState.connected;
});
}
从哪里调用连接方法:
bool isConnected = await FlutterBLE.connect(device);
if(isConnected) {
... Do some stuff ...
} else {
... Do some other stuff ...
}
我在这里做错了什么?
解决方案
正如 Günther Zöchbauer 所指出的那样,错误在于onDone
部分。您正在返回一个没有人会看到的值,并且您没有从周围的函数返回任何内容。
您位于异步函数中,因此您可以使用它await for
来迭代流。您还希望在第一次收到连接事件时停止收听流,因为您只关心第一次连接。连接事件流本身永远不会停止。
static Future<bool> connect(BluetoothDevice d) async {
// Connect to device
Duration timeout = const Duration(seconds: 5);
await for (var s in _flutterBlue.connect(d, timeout: timeout)) {
deviceState = s;
if (s == BluetoothDeviceState.connected) {
device = d;
device.discoverServices().then((s) {
... Some service discovery stuff ...
});
return true;
}
}
// The stream ended somehow, there will be no further events.
return false;
}
如果您不想使用await for
(并且不使用 async 函数开始),我建议您使用firstWhere
在以下位置查找第一个连接(如果有)listen
:
static Future<bool> connect(BluetoothDevice d) {
// Connect to device
Duration timeout = const Duration(seconds: 5);
return _flutterBlue.connect(d, timeout: timeout).firstWhere((s) {
return s == BluetoothDeviceState.connected;
}, orElse: () => null).then((s) {
if (s == null) return false;
deviceState = s;
device = d;
device.discoverServices().then((s) {
//... Some service discovery stuff ...
});
return true;
});
没有人等待返回的未来也有点可疑device.discoverServices().then(...)
。确保这是正确的。
推荐阅读
- graph - 风暴拓扑的操作
- ios - 在 UI 生命周期的哪个时间点,分隔线作为子视图添加到 UITableViewCells?
- apache-kafka - 同一组中的两个 kafka 消费者和一个分区
- php - 将 PDF 转换为 JPEG 会生成非常大的 /tmp 文件(使用 GMAGICK)
- mongodb - 如何在 AWS 上部署 Mongo 数据库?
- prolog - 如何解决此序言代码中的错误
- java - Mapstruct - 将包含和接口的对象转换为自己
- r - 根据名称中包含模式的列在 dplyr 中构建 rowSums
- ruby-on-rails - 在 Rails 中将 MiniMagick::Image 转换为 ActionDispatch::Http::UploadedFile
- python - 为什么我会收到不可为空的字段错误,并且要更正用户 ForeignKey 以将表相互关联?