Ble Result
A discriminated union that encapsulates the result of a BLE operation.
This sealed class provides a type-safe way to handle both successful results and failures from BLE operations without using nullable types or exceptions for control flow.
Design Philosophy
BleResult is inspired by Kotlin's Result class but is specifically designed for BLE operations with BleException as the failure type. This provides:
Type safety: The compiler ensures all failure cases are handled
Explicit error handling: Errors are part of the return type, not hidden
Functional composition: Chain operations with map, flatMap, etc.
No exceptions for control flow: Cleaner code without try-catch blocks
Usage Examples
Basic Usage
val result = connection.readCharacteristicResult(serviceUuid, charUuid)
when (result) {
is BleResult.Success -> {
val data = result.data
processData(data)
}
is BleResult.Failure -> {
val error = result.error
handleError(error)
}
}Functional Style
connection.readCharacteristicResult(serviceUuid, charUuid)
.map { bytes -> String(bytes, Charsets.UTF_8) }
.onSuccess { text -> displayText(text) }
.onFailure { error -> showError(error.message) }Chaining Operations
connection.readCharacteristicResult(serviceUuid, charUuid)
.flatMap { data ->
parseResponse(data)?.let { bleSuccess(it) }
?: bleFailure(BleCharacteristicException("Invalid response format"))
}
.onSuccess { parsedData -> process(parsedData) }Extracting Values
// Safe extraction (returns null on failure)
val data: ByteArray? = result.getOrNull()
// With default value
val data: ByteArray = result.getOrDefault(byteArrayOf())
// Throws on failure
val data: ByteArray = result.getOrThrow()Parameters
The type of the success value.
See also
Inheritors
Types
Properties
Functions
Returns the success value if this is a Success, or the defaultValue if this is a Failure.
Returns the success value if this is a Success, or the result of defaultValue if this is a Failure.
Transforms the error using the given transform function.
Recovers from a failure by providing an alternative success value.
Attempts to recover from a failure using another BleResult.