chunk
Collects the flow of data and emits a new flow of chunked data using the given operation.
This operator can be used to split data into smaller chunks suitable for transmission. The implementation of the operation is application-specific. Most common use cases are:
Splitting data into fixed-size packets (
MTU - 3bytes).Splitting data into packets with a header with total length.
Splitting data with flag in each chunk (single, first, middle, or last packet).
Example
val dataFlow: Flow<ByteArray> = ...
val chunkedFlow = dataFlow.chunk(20) { data, size ->
val header = data.size.toUShort().toByteArray(order = ByteOrder.BIG_ENDIAN)
val dataWithHeader = header + data
dataWithHeader.chunked(size)
}See Kotlin Util Library / data for extension functions to convert numbers to byte arrays.
Return
A flow of chunked data.
Parameters
The maximum size of a chunk.
The operation that will split the data into chunks.
Collects the flow of data and emits a new flow of packet of at-most given size.
This operator can be used to split data into smaller chunks suitable for transmission.
The data is split into chunks of given size. The last chunk may be shorter.
Example
val maxSize = peripheral.maximumWriteValueLength(writeType = WriteType.WITHOUT_RESPONSE)
val dataFlow: Flow<ByteArray> = ...
dataFlow
.chunk(maxSize)
.onEach { chunk ->
// Send the chunk to the peripheral.
}
.launchIn(scope)Return
A flow of packets.
Parameters
The maximum size of a packet.