subscribe

abstract fun subscribe(onSubscription: suspend RemoteCharacteristic.() -> Unit = {}): Flow<ByteArray>

Subscribes for notifications or indications of the characteristic.

If not already enabled, this method enables notifications or indications automatically on subscription, that is when a terminal operator (collect, first, etc.) is invoked on the returned flow.

onSubscription callback is invoked when the notifications or indications have been enabled successfully.

If higher-level packets are sent as multiple notifications or indications, they may be merged using merge or mergeIndexed operator.

// The Completable Deferred allows to synchronously await until the notifications are enabled.
val deferred = CompletableDeferred<Unit>()

// Enable notifications or indications and handle them.
remoteCharacteristic
.subscribe {
// Notifications are enabled and being collected.
deferred.complete(Unit)
}
// Catch subscription errors, i.e. OperationFailedException(reason=Subscribe not permitted)
.catch {
deferred.completeExceptionally(it)
}
// If a packet is split into multiple notifications, merge them.
.merge { accumulated, received ->
// [...]
}
// Transform the response raw data to a meaningful value.
.map { bytes -> parse(bytes) }
.onEach { data ->
// [...]
}
.launchIn(scope)
// Synchronously await until the notifications are enabled while still collecting them.
deferred.await()

This way no notification or indication will be missed, and it is clear when the characteristic is ready (connected, subscribed, triggered to send data).

Return

A flow emitting the raw data of notifications or indications sent from the characteristic when the value changes. The flow completes when the characteristic is invalidated, e.g., when the peripheral disconnects, or sends a Service Changed event.

Parameters

onSubscription

An optional callback that is invoked when the notifications or indications have been enabled successfully.

See also

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.