scanBluetoothDevice method Null safety

  1. @override
Stream<BluetoothDevice> scanBluetoothDevice(
  1. {Duration timeout = const Duration(seconds: 30)}
)
override

扫描蓝牙设备 timeout 超时时间

Implementation

@override
Stream<BluetoothDevice> scanBluetoothDevice(
    {Duration timeout = const Duration(seconds: 30)}) async* {
  StreamController? controller;
  StreamSubscription? subscription;
  bool cancelSubscription = false;
  if (_scanBluetoothDeviceStreamController?.isClosed == false) {
    await _scanBluetoothDeviceStreamController?.close();
    _scanBluetoothDeviceStreamController = null;
  }
  controller = StreamController(onListen: () {
    Future.delayed(timeout, () {
      if (!cancelSubscription) {
        cancelSubscription = true;
        controller?.close();
        stopScanBlueToothDevice();
        subscription?.cancel();
        _scanBluetoothDeviceStreamController = null;
      }
    });
  }, onCancel: () {
    if (!cancelSubscription) {
      cancelSubscription = true;
      stopScanBlueToothDevice();
      subscription?.cancel();
      _scanBluetoothDeviceStreamController = null;
    }
  });
  _scanBluetoothDeviceStreamController = controller;
  await methodChannel.invokeMethod(PluginConstants.methodScanBluetoothDevice);
  subscription = _bluetoothDeviceChannel.receiveBroadcastStream().listen(
      controller.add,
      onError: controller.addError,
      onDone: controller.close,
      cancelOnError: true);
  yield* controller.stream
      .map((e) => proto.BluetoothDevice.fromBuffer(e))
      .map((e) => BluetoothDevice.fromProto(e));
}