@@ -2,12 +2,15 @@ package com.juul.kable
22
33import co.touchlab.stately.collections.IsoMutableList
44import co.touchlab.stately.isolate.IsolateState
5+ import com.juul.kable.ObservationEvent.CharacteristicChange
6+ import com.juul.kable.ObservationEvent.Error
57import com.juul.kable.logs.Logging
68import kotlinx.coroutines.flow.Flow
79import kotlinx.coroutines.flow.MutableSharedFlow
810import kotlinx.coroutines.flow.filter
9- import kotlinx.coroutines.flow.map
11+ import kotlinx.coroutines.flow.mapNotNull
1012import kotlinx.coroutines.flow.onCompletion
13+ import kotlinx.coroutines.flow.onEach
1114import kotlinx.coroutines.flow.onSubscription
1215import kotlin.coroutines.cancellation.CancellationException
1316
@@ -38,6 +41,7 @@ internal class Observers<T>(
3841 private val peripheral : Peripheral ,
3942 private val logging : Logging ,
4043 extraBufferCapacity : Int = 0 ,
44+ private val exceptionHandler : ObservationExceptionHandler ,
4145) {
4246
4347 val characteristicChanges = MutableSharedFlow <ObservationEvent <T >>(extraBufferCapacity = extraBufferCapacity)
@@ -60,10 +64,26 @@ internal class Observers<T>(
6064 }
6165
6266 return characteristicChanges
63- .onSubscription { observation.onSubscription(onSubscription) }
67+ .onSubscription {
68+ try {
69+ observation.onSubscription(onSubscription)
70+ } catch (e: Exception ) {
71+ exceptionHandler(ObservationExceptionPeripheral (peripheral), e)
72+ }
73+ }
6474 .filter { event -> event.isAssociatedWith(characteristic) }
65- .map(::dematerialize)
66- .onCompletion { observation.onCompletion(onSubscription) }
75+ .onEach { event ->
76+ if (event is Error )
77+ exceptionHandler(ObservationExceptionPeripheral (peripheral), event.cause)
78+ }
79+ .mapNotNull { event -> (event as ? CharacteristicChange )?.data }
80+ .onCompletion {
81+ try {
82+ observation.onCompletion(onSubscription)
83+ } catch (e: Exception ) {
84+ exceptionHandler(ObservationExceptionPeripheral (peripheral), e)
85+ }
86+ }
6787 }
6888
6989 suspend fun onConnected () {
@@ -74,7 +94,7 @@ internal class Observers<T>(
7494 } catch (cancellation: CancellationException ) {
7595 throw cancellation
7696 } catch (e: Exception ) {
77- characteristicChanges.emit(ObservationEvent . Error (characteristic, e))
97+ characteristicChanges.emit(Error (characteristic, e))
7898 }
7999 }
80100 }
0 commit comments