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("")}")
}
}Content copied to clipboard