@@ -34,16 +34,20 @@ import com.juul.kable.logs.Logging.DataProcessor.Operation
3434import com.juul.kable.logs.detail
3535import kotlinx.coroutines.CoroutineName
3636import kotlinx.coroutines.CoroutineScope
37+ import kotlinx.coroutines.CoroutineStart.UNDISPATCHED
38+ import kotlinx.coroutines.Job
3739import kotlinx.coroutines.SupervisorJob
3840import kotlinx.coroutines.flow.Flow
3941import kotlinx.coroutines.flow.MutableStateFlow
4042import kotlinx.coroutines.flow.StateFlow
4143import kotlinx.coroutines.flow.asStateFlow
44+ import kotlinx.coroutines.flow.collect
4245import kotlinx.coroutines.flow.filter
4346import kotlinx.coroutines.flow.launchIn
4447import kotlinx.coroutines.flow.onEach
4548import kotlinx.coroutines.flow.update
4649import kotlinx.coroutines.job
50+ import kotlinx.coroutines.launch
4751import kotlinx.coroutines.withContext
4852import kotlin.coroutines.CoroutineContext
4953import kotlin.coroutines.cancellation.CancellationException
@@ -106,6 +110,7 @@ internal class BluetoothDeviceAndroidPeripheral(
106110
107111 private suspend fun establishConnection (scope : CoroutineScope ) {
108112 checkBluetoothAdapterState(expected = STATE_ON )
113+ bluetoothState.watchForDisablingIn(scope)
109114
110115 logger.info { message = " Connecting" }
111116 _state .value = State .Connecting .Bluetooth
@@ -141,21 +146,21 @@ internal class BluetoothDeviceAndroidPeripheral(
141146 logger.info { message = " Connected" }
142147 _state .value = State .Connected
143148
144- bluetoothState.watchForDisablingIn(scope)
145149 state.watchForConnectionLossIn(scope)
146150 }
147151
148- private fun Flow<Int>.watchForDisablingIn (scope : CoroutineScope ) =
149- filter { state -> state == STATE_TURNING_OFF || state == STATE_OFF }
150- .onEach { state ->
151- logger.debug {
152- message = " Bluetooth disabled"
153- detail(" state" , state)
152+ private fun Flow<Int>.watchForDisablingIn (scope : CoroutineScope ): Job =
153+ scope.launch(start = UNDISPATCHED ) {
154+ filter { state -> state == STATE_TURNING_OFF || state == STATE_OFF }
155+ .collect { state ->
156+ logger.debug {
157+ message = " Bluetooth disabled"
158+ detail(" state" , state)
159+ }
160+ closeConnection()
161+ throw BluetoothDisabledException ()
154162 }
155- closeConnection()
156- throw BluetoothDisabledException ()
157- }
158- .launchIn(scope)
163+ }
159164
160165 private fun Flow<State>.watchForConnectionLossIn (scope : CoroutineScope ) =
161166 state
0 commit comments