· 6 min read
Kotlin Flow for BLE Responses: Subscribe Before You Write
How to turn Android BLE notifications into a Kotlin Flow and wait for a response without losing it to a race, with a Mutex, a timeout and a test.
Android BLE gives you callbacks. The rest of a modern Android app speaks coroutines and Kotlin Flow. The gap between them is where the bugs hide. At Gatewise I work on the Android app that talks to smart locks over Bluetooth Low Energy, and we use Kotlin Flow in production to receive BLE responses from the lock. The pattern is simple: send a command, wait for the matching notification. The trap is just as simple: if you start waiting after you send, a fast device can answer before anyone is listening, and the response is gone.
This post shows the small pattern I use: one stream for all notifications, a request function that subscribes before it writes, one request at a time, a timeout, and a unit test that proves the race is fixed. I keep any real lock protocol out of it. The bytes below are made up, and the pattern works for any BLE device.
The problem: GATT callbacks vs suspend functions
On Android, everything that comes back from a BLE device arrives through one BluetoothGattCallback. Notifications land in onCharacteristicChanged. Writes confirm in onCharacteristicWrite. These calls come on a Binder thread, not on your coroutine.
What the rest of the app wants is one line:
val reply = lockClient.request(command)
A suspend function that sends a command and returns the answer. ViewModels, use cases and tests all get simpler when the BLE layer looks like this. The work is in the bridge between the callback and that function.
One Kotlin Flow for all BLE notifications
The first step is to push every notification into a single hot stream. A MutableSharedFlow fits: it has no initial value, many collectors can read it, and tryEmit is safe to call from the callback thread.
class GattLink(/* gatt, characteristics */) : BleLink {
private val _notifications = MutableSharedFlow<ByteArray>(
extraBufferCapacity = 64,
)
override val notifications: Flow<ByteArray> = _notifications
val callback = object : BluetoothGattCallback() {
override fun onCharacteristicChanged(
gatt: BluetoothGatt,
characteristic: BluetoothGattCharacteristic,
value: ByteArray,
) {
if (!_notifications.tryEmit(value.copyOf())) {
Log.w(TAG, "BLE notification dropped: buffer full")
}
}
}
override suspend fun write(bytes: ByteArray) {
// gatt.writeCharacteristic(...) and wait for onCharacteristicWrite
}
}
Three details matter here:
extraBufferCapacity. Without a buffer,tryEmitfails as soon as a collector is slow. A small buffer absorbs bursts. Log when it still fails, so you see it instead of guessing.copyOf(). Do not hand out an array the system might reuse. Copying a few bytes is cheap.- The
BleLinkinterface. The client code depends onnotificationsandwrite, not onBluetoothGatt. That is what makes the test at the end possible.
The callback signature above is the one added in Android 13 (API 33). Older versions use the overload that reads characteristic.value. The Android BLE data transfer guide covers both.
Subscribe before you write: the race in Kotlin SharedFlow
Here is the first version most of us write:
// Looks fine. Loses responses.
suspend fun request(command: ByteArray): ByteArray {
link.write(command)
return link.notifications.first { it.isReplyTo(command) }
}
A SharedFlow with no replay does not keep values for collectors that arrive later. If the device answers while write is still finishing, the notification is emitted with no one subscribed, and it is dropped. Then first waits forever for an answer that already came.
On a desk, with a slow debug build, this almost never happens. It shows up later, on a fast phone close to the device, as a request that "sometimes hangs".
The fix is to start listening first, then write:
suspend fun request(command: ByteArray): ByteArray = coroutineScope {
val reply = async(start = CoroutineStart.UNDISPATCHED) {
link.notifications.first { it.isReplyTo(command) }
}
link.write(command)
reply.await()
}
CoroutineStart.UNDISPATCHED runs the async block right away, on the current thread, until its first suspension point. That point is inside first, after it has subscribed to the shared flow. So by the time write is called, the collector is already registered and nothing can slip past it.
A plain async without that flag is not enough. It schedules the block for later, and write can run first.
One request at a time, with a timeout
Two more rules turn this into something you can ship.
Serialize requests. Android's GATT layer handles one operation at a time. And if two requests wait on the same stream, one can take the other's reply. A Mutex keeps it simple: one request in flight per connection.
Always time out. Devices go out of range, firmware gets busy, a notification gets lost. A request without a timeout is a coroutine that never ends and a spinner that never stops.
class LockClient(
private val link: BleLink,
private val timeout: Duration,
) {
private val mutex = Mutex()
suspend fun request(command: ByteArray): ByteArray = mutex.withLock {
withTimeout(timeout) {
coroutineScope {
val reply = async(start = CoroutineStart.UNDISPATCHED) {
link.notifications.first { it.isReplyTo(command) }
}
link.write(command)
reply.await()
}
}
}
}
withTimeout throws a TimeoutCancellationException and cancels the scope inside it, so the waiting async is cleaned up too. Catch the timeout at the layer that knows what to tell the user, not here. Pick the timeout value from what your device actually needs, and keep it in config, not buried in the call.
isReplyTo is your matching rule. In the simplest case it compares a command ID in the first byte. Write it as a plain function, so it is easy to unit test on its own.
Test the race with a fake link
The race is the whole point, so the test should reproduce it on purpose. A fake BleLink that answers inside write, before write returns, is the worst case: the reply comes as early as it possibly can.
class FakeLink : BleLink {
private val flow = MutableSharedFlow<ByteArray>(extraBufferCapacity = 8)
override val notifications: Flow<ByteArray> = flow
var onWrite: (ByteArray) -> Unit = {}
override suspend fun write(bytes: ByteArray) {
onWrite(bytes)
}
fun emit(bytes: ByteArray) {
flow.tryEmit(bytes)
}
}
@Test
fun `reply that arrives during write is not lost`() = runTest {
val link = FakeLink()
link.onWrite = { cmd -> link.emit(byteArrayOf(cmd[0], 0x00)) }
val client = LockClient(link, timeout = 1.seconds)
val reply = client.request(byteArrayOf(0x07))
assertEquals(0x07.toByte(), reply[0])
}
@Test
fun `request times out when the device is silent`() = runTest {
val client = LockClient(FakeLink(), timeout = 1.seconds)
assertFailsWith<TimeoutCancellationException> {
client.request(byteArrayOf(0x07))
}
}
Run the first test against the "write, then wait" version and it fails with a timeout. Run it against the version that subscribes first and it passes. That is the kind of test I like: it fails for the exact bug it is named after.
The second test runs fast because runTest uses virtual time. The one-second timeout does not cost a real second.
These are plain JUnit tests with kotlinx-coroutines-test. No device, no emulator, no Bluetooth. The real GattLink still needs testing on hardware, but the logic that decides which reply belongs to which request does not.
Takeaways
- Push every BLE notification into one
MutableSharedFlowwith a small buffer, and log whentryEmitfails. - Subscribe before you write. Use
async(start = CoroutineStart.UNDISPATCHED)so the collector is registered before the command goes out. - Allow one request in flight per connection with a
Mutex, and wrap every request inwithTimeout. - Hide
BluetoothGattbehind a small interface, so the request logic runs in plain JUnit tests. - Write a test where the fake device answers during the write. It is the cheapest way to prove the race is gone.
For more on how first, SharedFlow and cancellation work together, the Kotlin Flow guide is a good reference.