Skip to content

Commit

Permalink
Fix FlutterBlue.state stream cancel
Browse files Browse the repository at this point in the history
Fix bug where if there were multiple subscribers to FlutterBlue.state
and one cancelled it would accidentally cancel all subscribers
Fix for: pauldemarco#608
  • Loading branch information
MacMalainey committed Jun 17, 2020
1 parent 63a1002 commit 6fba536
Showing 1 changed file with 11 additions and 2 deletions.
13 changes: 11 additions & 2 deletions lib/src/flutter_blue.dart
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,13 @@ class FlutterBlue {
Stream<MethodCall> get _methodStream => _methodStreamController
.stream; // Used internally to dispatch methods from platform.

/// Fix for issue #608
/// Cached broadcast stream for FlutterBlue.state events
/// Caching this stream allows for more than one listener to subscribe
/// and unsubscribe apart from each other,
/// while allowing events to still be sent to others that are subscribed
Stream<BluetoothState> _stateStream;

/// Singleton boilerplate
FlutterBlue._() {
_channel.setMethodCallHandler((MethodCall call) {
Expand Down Expand Up @@ -51,10 +58,12 @@ class FlutterBlue {
.then((buffer) => new protos.BluetoothState.fromBuffer(buffer))
.then((s) => BluetoothState.values[s.state.value]);

yield* _stateChannel
_stateStream ??= _stateChannel
.receiveBroadcastStream()
.map((buffer) => new protos.BluetoothState.fromBuffer(buffer))
.map((s) => BluetoothState.values[s.state.value]);
.map((s) => BluetoothState.values[s.state.value]).doOnCancel(() => _stateStream = null);

yield* _stateStream;
}

/// Retrieve a list of connected devices
Expand Down

0 comments on commit 6fba536

Please sign in to comment.