Concurrency and lifecycle#

BrainAccessKit uses Swift structured concurrency.

Async surface#

Concurrency primitives#

Need

Type

Stream of EEG chunks

AsyncThrowingStream<EegChunk, Error>

Observable state

CurrentValue<T> (value plus replaying stream)

Fallible asynchronous call

async returning Result

GATT operations

per-peripheral serialized operation queue over CoreBluetooth callbacks

Cancellation is the stop signal. Cancelling a task that iterates DeviceSession.stream() stops the device stream: the STREAM_STOP write runs in a task that is not cancelled, after the session’s time-sync ping in flight, if any, has finished. Cancelling a scan task stops scanning when the iterator is released.

GattConnection states the matching contract for transports: an attribute op (read, readTimed, write, setNotify) already issued is never abandoned — it finishes, answered, failed or timed out by the transport’s own bound, whatever happens to its caller’s task, because an op abandoned in flight leaves the platform’s GATT client busy and the ops after it fail. A transport may refuse an op called from an already-cancelled task with CancellationError; CoreBluetoothTransport does not, the test fake does. A teardown write that must go out therefore runs in an unstructured Task.

Backpressure#

The SDK does not silently drop decoded chunks. Consumers own backpressure: process chunks quickly, hand them to a worker, or add a bounded app-side buffer and account for any drops there. Device-side loss is different: the codec gap-fills missing device sample indices and surfaces them as EegChunk.isDummy plus DeviceSession.missedSamples. Firmware 3.8.x also numbers the conversions its own reader missed, so on it missedSamples includes those losses, which older firmware hid.

Multiple devices#

BrainAccessClient owns one scanner and a map of sessions keyed by DeviceId. The scanner is independent of connected sessions, so scan-while-connected is supported. Multiple sessions can run in parallel; the practical ceiling is BLE airtime and device/phone behavior, not an SDK hard cap. Continuity degradation appears as gap-filled samples.

SwiftUI pattern#

import SwiftUI
import BrainAccessKit

@MainActor
final class DeviceListModel: ObservableObject {
    @Published var names: [String] = []
    private let client = BrainAccessClient(transport: CoreBluetoothTransport())
    private var scanTask: Task<Void, Never>?

    func startScanning() {
        scanTask?.cancel()
        scanTask = Task { [client] in
            for await device in client.scan() {
                await MainActor.run { self.names.append(device.name) }
            }
        }
    }

    func stopScanning() {
        scanTask?.cancel()
        scanTask = nil
    }
}