From 6fba5360d80a56dc9755ac5a7acbe9b9ee632b09 Mon Sep 17 00:00:00 2001 From: Mackenzie Malainey Date: Tue, 16 Jun 2020 18:13:29 -0600 Subject: [PATCH] Fix FlutterBlue.state stream cancel Fix bug where if there were multiple subscribers to FlutterBlue.state and one cancelled it would accidentally cancel all subscribers Fix for: https://github.com/pauldemarco/flutter_blue/issues/608 --- lib/src/flutter_blue.dart | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/lib/src/flutter_blue.dart b/lib/src/flutter_blue.dart index e5aff0a0..24a6cc01 100644 --- a/lib/src/flutter_blue.dart +++ b/lib/src/flutter_blue.dart @@ -12,6 +12,13 @@ class FlutterBlue { Stream 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 _stateStream; + /// Singleton boilerplate FlutterBlue._() { _channel.setMethodCallHandler((MethodCall call) { @@ -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