merge

fun Flow<ByteArray>.merge(operation: suspend (accumulator: ByteArray, received: ByteArray) -> MergeResult): Flow<ByteArray>

Collects the flow of packets and emits a new flow of merged data using the given operation.

This operator can be used to combine data received in multiple chunks into a single message. The implementation of the operation is application-specific. Most common use cases are:

  • Known length of the message.

  • Message with a header that contains the length of the message.

  • Each packet contains a flag indicating single, first, middle, or last packet.

  • Trying to parse the message (e.g. convert to a valid JSON) after each chunk.

On the first run, the accumulator array will be empty. The method should return MergeResult.Accumulate if more data is expected. The MergeResult.Accumulate.accumulated array will be passed as the accumulator parameter in the next call when more data is received.

Return MergeResult.Completed when the full message has been received to emit the result.

Return

A flow of merged data.

Parameters

operation

The operation that will merge the data.