Possible issue with using ReplayingShare to share connections
See original GitHub issueThis is more of a question or discussion, not an issue, since it doesn’t relate to any of the RxAndroidBle code. However, it does relate to the recommendation to use ReplayingShare
instead of the ConnectionShareAdapter
.
This is the issue.
- A device was just scanned.
- The device is recognized and grabbed.
- Then
establishConnection
is called on this device and shared through the use ofReplayingShare
. The resulting shared Rx observable is cached in the code that grabbed the device. - Say an observer subscribes to the above shared Rx observable and then flat-maps with a
connection.readCharacteristic
. All goes well, data is read hand handled. - Then there is an issue with the Bluetooth adapter or reception, but it is quickly resolved. However, the current connection is no longer valid. It is stale, the device is disconnected. The current observer receives an onError and handles the disconnection error.
- A little later a second observer subscribes to the above shared Rx observable.
- Since this shared Rx observable uses the
ReplayingShare
, the second subscription causes an invalid/stale connection to be emitted by theReplayingShare
.
The problem is that ReplayingShare
does not react to finalizations (onComplete, onError or onDispose). This means that ReplayingShare
cannot be used to share resources that become invalid/stale as soon as subscriptions to these resources are finalized. The RxBleConnection
is such a resource.
In our project, I worked around this by copying the ReplayingShare
code and add a little bit of code:
In the two apply
methods of the ReplayingShare
, I changed this
upstream.doOnNext(lastSeen).share()
to thisupstream.doFinally { lastSeen.value = null }.doOnNext(lastSeen).share()
This prevents invalid/state RxBleConnection
s to be emitted and solved the issues we had with concurrent connections.
Issue Analytics
- State:
- Created 5 years ago
- Comments:21 (3 by maintainers)
Top GitHub Comments
I discussed this with Jake Wharton and he agrees there’s a problem. He’s mulling over the solution.
I touched base with Wharton recently and he said that he should soon have time to work on this.