Home > Enterprise >  Flutter - an async function returns before really finishing?
Flutter - an async function returns before really finishing?

Time:01-22

I have a function scanAndConnect() that should scan for BLE devices and connect to the device with the specified service ID. This function should be async and should return Future.

The problem is that scanAndConnect() prints 99999 and returns without waiting for flutterReactiveBle.statusStream.listen() to finish although I use await before it.

Future scanAndConnect(Uuid serviceId, Uuid charctId) async {
    StreamSubscription<BleStatus>? bleStatusStreamSubscription;
    StreamSubscription<DiscoveredDevice>? deviceStreamSubscription;
    Stream<DiscoveredDevice> stream;
    bleStatusStreamSubscription =
        await flutterReactiveBle.statusStream.listen((bleStatus) async {
      print("new listen ${bleStatus.toString()}");
      if (bleStatus == BleStatus.ready) {
        await bleStatusStreamSubscription!.cancel();
        connectionStatus = BLEConnectionStatus.Connecting;
        stream = await flutterReactiveBle.scanForDevices(
          withServices: [serviceId],
          scanMode: ScanMode.lowLatency,
        );
      }
    });

    print("9999999");
  }

....

Future connectToDevice() async {
  await ble.scanAndConnect(BLE_SERVICE_UUID, BLE_CHAR_UUID)
  print("Statement after await in main");
  setState(() {
    loading = false;
    print("Changing state to ${loading.toString()}");
  });
}

This is the output I get in Xcode:

flutter: 9999999
flutter: Statement after await in main
flutter: Changing state to false
flutter: new listen BleStatus.unknown
flutter: new listen BleStatus.ready

How can I make scanAndConnect doesn't return before really finishing?

CodePudding user response:

According to the documentation, FlutterReactiveBle.scanForDevices() returns a Stream, not a Future, so await will not work here. You can use

  • await for
  • listen()
  • await stream.first()

to wait for data from a Stream.

  • Related