CollectHandler

Handler for collecting a Flow with explicit callbacks for chunks, errors, and completion.

Useful when you need to handle streaming responses with separate actions for each event without using traditional collect{} blocks.

Type Parameters

T

The type of items in the flow.

Samples

// Create a list for full model output.
val modelOutput = mutableListOf<String>()

// Collect and handle flow events.
chunksFlow.collectHandler {
    onChunk { chunk ->
        val firstChoice = chunk.choices.first()

        when (val content = firstChoice.content) {
            is Content.Reasoning -> println("Reasoning: ${content.value}")
            is Content.Text -> {
                modelOutput.add(content.text)
                println(content.text)
            }
            is Content.ToolCallDelta -> println("ToolCall: ${content.name} with args: ${content.argumentsChunk}")
        }
    }
    onError { error ->
        // Error handling.
        println("Error in ${error::class.simpleName}: ${error.message}")
    }
    onCompleted {
        // Print full output.
        println("Completed! Full output:\n${modelOutput.joinToString("")}")
    }
}

Constructors

Link copied to clipboard
constructor()

Functions

Link copied to clipboard
suspend fun collectFrom(flow: Flow<T>)

Collects the flow and triggers registered callbacks.

Link copied to clipboard
fun onChunk(action: suspend (T) -> Unit)

Registers a callback for each emitted item.

Link copied to clipboard
fun onCompleted(action: suspend () -> Unit)

Registers a callback for completion.

Link copied to clipboard
fun onError(action: suspend (Throwable) -> Unit)

Registers a callback for errors.