cancelWhenDisconnected method

void cancelWhenDisconnected(
  1. StreamSubscription subscription, {
  2. bool next = false,
  3. bool delayed = false,
})

Register a subscription to be canceled when the device is disconnected. This function simplifies cleanup, so you can prevent creating duplicate stream subscriptions.

  • this is an optional convenience function
  • prevents accidentally creating duplicate subscriptions on each reconnection.
  • next if true, the the stream will be canceled only on the next disconnection. This is useful if you setup your subscriptions before you connect.
  • delayed Note: This option is only meant for connectionState subscriptions. When true, we cancel after a small delay. This ensures the connectionState listener receives the disconnected event.

Implementation

void cancelWhenDisconnected(StreamSubscription subscription,
    {bool next = false, bool delayed = false}) {
  if (isConnected == false && next == false) {
    subscription.cancel(); // cancel immediately if already disconnected.
  } else if (delayed) {
    FlutterBluePlus._delayedSubscriptions[remoteId] ??= [];
    FlutterBluePlus._delayedSubscriptions[remoteId]!.add(subscription);
  } else {
    FlutterBluePlus._deviceSubscriptions[remoteId] ??= [];
    FlutterBluePlus._deviceSubscriptions[remoteId]!.add(subscription);
  }
}