This is the consuming part:
val scope = CoroutineScope(Job() + <http://Dispatchers.IO|Dispatchers.IO>)
val readerFlow = merge(disconnectedFlow, acsBluetoothReaderManager.onReaderDetection())
scope.launch {
readerFlow.onEach {
Log.d("BTM", "Got a new reader to collect: $it")
}
.collectLatest { reader ->
The producing part:
private val disconnectedFlow: MutableStateFlow<BluetoothReaderSupport?> = MutableStateFlow(null)
private fun disconnectedCallback() {
Log.d("BTM", "Disconnected Callback")
val scope = CoroutineScope(Job())
scope.launch {
disconnectedFlow.emit(null)
}
}
The other producing part:
fun BluetoothReaderManager.onReaderDetection(): Flow<BluetoothReaderSupport?> {
val brm = this
return callbackFlow<BluetoothReaderSupport?> {
brm.setOnReaderDetectionListener { reader ->
trySendBlocking(BluetoothReaderSupport(reader))
.onSuccess { Log.d("BluetoothSupport", "Forwarded new reader: $reader") }
.onFailure { exception -> throw exception!! }
}
awaitClose { brm.setOnReaderDetectionListener(null) }
}
}
```