setNotifying
Enables notifications or indications, depending on the characteristic's properties.
This method writes to the Client Characteristic Configuration Descriptor (CCCD) belonging to this characteristic to enable or disable notifications or indications.
Note: subscribe or waitForValueChange enable notifications automatically.
Example
This snippet shows how the notifications can be enabled and disabled synchronously:
remoteCharacteristic.setNotifying(true)
println("Notifications are enabled: ${remoteCharacteristic.isNotifying}") // -> trueRace Condition Warning
Using setNotifying(true) can lead to a race condition where the peripheral sends a notification before the app is ready to collect it, causing the first value to be missed.
It is strongly recommended to use subscribe or waitForValueChange instead. These Flow-based APIs guarantee that the listener is active before notifications are enabled on the peripheral, preventing data loss.
Example
remoteCharacteristic
.subscribe {
// Here, the notifications are 100% enabled.
println("Notifications are enabled: ${remoteCharacteristic.isNotifying}") // -> true
}
.catch {
// Catch an exception if subscribe() failed.
}
.collect {
// [...]
}
// The Flow is cold. Notifications are not yet enabled.
println("Notifications are enabled: ${remoteCharacteristic.isNotifying}") // -> falseParameters
True to enable notifications or indications, false to disable them.
Throws
if the operation failed.
if the characteristic has been invalidated due to disconnection or service change event.
if the implementation fails, see BluetoothException.cause for a reason.