Short answer: expose connection state as a StateFlow and incoming notifications as a SharedFlow fed from your BluetoothGattCallback. Your ViewModel then collects them like any other Flow and the GATT object stays in one class.
The idea
The GATT callback runs on a Binder thread. Instead of passing it around, have the callback push events into flows owned by a manager class.
BLE manager
sealed interface BleState {
object Disconnected : BleState
object Connecting : BleState
object Connected : BleState
data class Error(val status: Int) : BleState
}
class BleManager(private val context: Context) {
private val _state = MutableStateFlow<BleState>(BleState.Disconnected)
val state: StateFlow<BleState> = _state
private val _data = MutableSharedFlow<ByteArray>(extraBufferCapacity = 64)
val data: SharedFlow<ByteArray> = _data
private var gatt: BluetoothGatt? = null
private val callback = object : BluetoothGattCallback() {
override fun onConnectionStateChange(g: BluetoothGatt, status: Int, newState: Int) {
if (status != BluetoothGatt.GATT_SUCCESS) {
_state.value = BleState.Error(status)
g.close()
return
}
if (newState == BluetoothProfile.STATE_CONNECTED) {
_state.value = BleState.Connected
g.discoverServices()
} else {
_state.value = BleState.Disconnected
g.close()
}
}
// Android 13+ (API 33)
override fun onCharacteristicChanged(
g: BluetoothGatt, c: BluetoothGattCharacteristic, value: ByteArray
) { _data.tryEmit(value) }
}
@SuppressLint("MissingPermission")
fun connect(device: BluetoothDevice) {
_state.value = BleState.Connecting
gatt = device.connectGatt(context, false, callback)
}
@SuppressLint("MissingPermission")
fun disconnect() { gatt?.disconnect() }
}
On Android 12 and lower, the older onCharacteristicChanged(gatt, characteristic) is the one called; override it too and emit characteristic.value.
Collect in a ViewModel
class BleViewModel(private val ble: BleManager) : ViewModel() {
val state = ble.state
init {
viewModelScope.launch {
ble.data.collect { bytes -> /* parse */ }
}
}
}
Tips
- Use
extraBufferCapacityso a fast sensor does not block the callback thread. - Inject the manager with Hilt as a singleton so there is one GATT client.
- Keep the operation queue from our BLE guide inside this class.
FAQ
StateFlow or SharedFlow?
StateFlow for state that always has a current value; SharedFlow for events like incoming packets.
Does collecting in the UI leak the connection?
Not if the manager owns the GATT object and the UI only collects flows.