fbpEnsureAdapterIsOn method

Future<T> fbpEnsureAdapterIsOn(
  1. String function
)

Implementation

Future<T> fbpEnsureAdapterIsOn(String function) {
  // Create a completer to represent the result of this extended Future.
  var completer = Completer<T>();

  // disconnection listener.
  var subscription = FlutterBluePlus.adapterState.listen((event) {
    if (event == BluetoothAdapterState.off || event == BluetoothAdapterState.turningOff) {
      if (!completer.isCompleted) {
        completer.completeError(FlutterBluePlusException(
            ErrorPlatform.fbp, function, FbpErrorCode.adapterIsOff.index, "Bluetooth adapter is off"));
      }
    }
  });

  // When the original future completes
  // complete our completer and cancel the subscription.
  then((value) {
    if (!completer.isCompleted) {
      subscription.cancel();
      completer.complete(value);
    }
  }).catchError((error) {
    if (!completer.isCompleted) {
      subscription.cancel();
      completer.completeError(error);
    }
  });

  return completer.future;
}