manolofdez / AsyncBluetooth

A small library that adds concurrency to CoreBluetooth APIs.
MIT License
168 stars 31 forks source link

characteristicValueUpdatedPublisher causes runtime warning in Swift 6 #60

Closed Dan1973KS closed 2 months ago

Dan1973KS commented 2 months ago

Your example to get notified by characteristics looks like this:

await peripheral.characteristicValueUpdatedPublisher .filter { $0.uuid == self.commandResponseUUID } .map { try? $0.parsedValue() as Data? } .sink { value in print(value) } .store(in: &cancellables)

When I implement it in an observable object using Swift 5 language mode it works fine! When I do the same in Swift 6 mode, the debugger reports a runtime warning that .sink is not called on MainActor: warning: data race detected: @MainActor function at ProGo_Konnekt/Notifier.swift:45 was not called on the main thread

Here is the caller from your framework: func peripheral(_ cbPeripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) { Task { if characteristic.isNotifying { await self.context.characteristicValueUpdatedSubject.send(Characteristic(characteristic)) } (...)

I guess that most of the subscribers will be on MainActor. So could it make sense to report the value updates on main thread?

manolofdez commented 2 months ago

Yeah, that makes a lot of sense to me. Let me open a PR...