【发布时间】:2018-07-17 21:11:19
【问题描述】:
我目前正在从蓝牙设备读取变量。这显然需要不确定的时间,所以我使用期货(这个方法在我下面的代码中是 readCharacteristic)。
一次不能进行多个读取操作 - 如果在第一个操作仍在进行时启动了第二个读取操作,Flutter 将抛出错误。
我的理解是,使用 .then() 将 future 链接在一起只会允许下一个语句在上一个调用完成时执行。这个想法似乎是正确的,直到我尝试读取第三个值 - 即由于重叠的读取事件而引发错误时。
这是我的代码:
readCharacteristic(scanDurationCharacteristic)
.then((list) => sensorScanDuration = list[0].toDouble())
.then((_) {
readCharacteristic(scanPeriodCharacteristic)
.then((list) => sensorScanPeriod = list[0].toDouble());
}).then((_) {
readCharacteristic(aggregateCharacteristic)
.then((list) => sensorAggregateCount = list[0].toDouble());
}).then((_) {
readCharacteristic(appEUICharacteristic)
.then((list) => appEUI = decimalToHexString(list));
}).then((_) {
readCharacteristic(devEUICharacteristic)
.then((list) => devEUI = decimalToHexString(list));
}).then((_) {
readCharacteristic(appKeyCharacteristic)
.then((list) => appKey = decimalToHexString(list));
});
有什么更好的方法来确保这些读取事件不会重叠?
【问题讨论】:
-
为什么要连锁?为什么不把它们全部并行呢?
-
并行读取会引发异常,所以我不能并行执行。
标签: dart flutter dart-async