-
Notifications
You must be signed in to change notification settings - Fork 11
Have onConnectionStateChange backed by StateFlow #66
Conversation
Codecov Report
@@ Coverage Diff @@
## develop #66 +/- ##
=============================================
+ Coverage 80.46% 80.70% +0.23%
Complexity 36 36
=============================================
Files 13 13
Lines 256 254 -2
Branches 28 26 -2
=============================================
- Hits 206 205 -1
+ Misses 43 42 -1
Partials 7 7
|
private val _onConnectionStateChange = MutableStateFlow<OnConnectionStateChange?>(null) | ||
val onConnectionStateChange: Flow<OnConnectionStateChange> = | ||
_onConnectionStateChange.filterNotNull() |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I agree it isn't ideal. I was torn on the best approach.
I considered exposing connection state as a simple sealed class
as is being done in KeepAliveGatt
:
sealed class State {
object Connecting : State()
object Connected : State()
object Disconnecting : State()
object Disconnected : State()
data class Closed(val cause: Throwable?) : State()
}
But I worried this would diverge too much from the current onConnectionStateChange
(in 0.7.x
) that carries GATT status (e.g. GATT_SUCCESS
) in addition to the connection state.
Being that OnConnectionStateChange
holds both the GATT status and connection state does make it more like an event than a state; so at first, does make SharedFlow
seem like a better fit.
I ultimately settled on StateFlow
because I saw the "connection state" as the primary attribute of the OnConnectionStateChange
, so I justified it as more of a state than event.
Making it nullable was necessary to simplify handling of the initial connection sequence:
During the connection sequence, if we see a STATE_DISCONNECTED
then we can consider the connection attempt as failed. If the StateFlow
were non-null
and we started it with a STATE_DISCONNECTED
then it would require more complexity to properly handle that case. Whereas making _onConnectionStateChange
(internally) nullable means we can represent the absence of a connection state as null
(before Android has called BluetoothGattCallback. onCharacteristicChanged
).
Although it may appear a bit awkward, it was was suggested as a possible approach in: Kotlin/kotlinx.coroutines#2034 (comment)
Changes
onConnectionStateChange
property to be backed byStateFlow
instead ofConflatedBroadcastChannel
: