连锁期货未按顺序执行

时间:2018-07-17 21:11:19

标签: dart flutter dart-async

我目前正在从Bluetooth设备读取变量。显然,这需要花费不确定的时间,因此我正在使用期货(此方法在下面的代码中为readCharacteristic)。

一次不能进行多个读取操作-如果在进行第一个操作的同时启动了第二个读取操作,Flutter将抛出错误。

我的理解是,使用.then()将期货链接在一起只会在下一个调用完成后才允许执行下一条语句。在我尝试读取第三个值之前,这个想法似乎是正确的-因为重叠的读取事件,引发了错误。

这是我的代码:

float 4466.54

有什么更好的方法来确保这些读取事件不会重叠?

2 个答案:

答案 0 :(得分:2)

如果要链接期货,则必须从上一个Future的return方法中then来使用上一个Future。

文档说要这样链接

expensiveA()
    .then((aValue) => expensiveB())
    .then((bValue) => expensiveC())
    .then((cValue) => doSomethingWith(cValue));

与...相同,

expensiveA()
    .then((aValue) {
        return expensiveB();
    }).then((bValue) {
        return expensiveC();
    }).then((cValue) => doSomethingWith(cValue));

这适用于您的情况,

readCharacteristic(scanDurationCharacteristic)
    .then((list) {
        sensorScanDuration = list[0].toDouble();
        return readCharacteristic(scanPeriodCharacteristic);
    }).then((list) {
        sensorScanPeriod = list[0].toDouble());
        return readCharacteristic(aggregateCharacteristic);
    }).then((list) {
        sensorAggregateCount = list[0].toDouble());
        return readCharacteristic(appEUICharacteristic);
    }).then((list) {
        appEUI = decimalToHexString(list));
        return readCharacteristic(devEUICharacteristic);
    }).then((list) {
        devEUI = decimalToHexString(list));
        return readCharacteristic(appKeyCharacteristic);
    }).then((list) => appKey = decimalToHexString(list));

答案 1 :(得分:1)

尽管R.C Howell的答案是正确的,但更喜欢使用async / await关键字。这更具可读性,而且您出错的可能性也较小

Future<void> scanBluetooth() async {
  sensorScanDuration = (await readCharacteristic(scanDurationCharacteristic))[0].toDouble();
  sensorScanPeriod = (await readCharacteristic(scanPeriodCharacteristic))[0].toDouble();
  sensorAggregateCount = (await readCharacteristic(aggregateCharacteristic))[0].toDouble();
  appEUI = await readCharacteristic(appEUICharacteristic).then(decimalToHexString);
  devEUI = await readCharacteristic(devEUICharacteristic).then(decimalToHexString);
  appKey = await readCharacteristic(appKeyCharacteristic).then(decimalToHexString);
}