Stream answers in the iOS SDK
Show an agent's answer as it is written by iterating the AsyncThrowingStream from OctoClient.streamChat, with cancellation and UI state tips.
Working draft. These docs are illustrative: names, endpoints and examples describe the intended behaviour and can change before launch.
Streaming sends the answer to your app in small pieces while the agent is still writing it. Customers see text appear after a moment instead of waiting for the full reply. Use streamChat for any chat screen where the answer can be more than a sentence long.
Iterate a stream
streamChat returns an AsyncThrowingStream of StreamEvent. Nothing is sent until you start iterating.
func ask(_ input: String) async {
var text = ""
do {
for try await event in octo.streamChat(text: input, conversationId: cid) {
switch event {
case .messageDelta(let piece):
text += piece
state = .writing(text)
case .messageDone(let message, _):
state = .done(message)
case .toolCall:
break
case .error(let error):
state = .failed(error)
}
}
} catch {
state = .failed(error as? OctoError)
}
}
Each .messageDelta holds the next piece of text. .messageDone arrives once with the complete Message, including its sources. Replace your partial text with that message so the final text always matches what the server stored.
What you should see
The first delta arrives shortly after the request starts. Deltas continue until .messageDone, then the loop ends. The streaming events page lists every case in detail.
Cancel a stream
The stream stops when the task that iterates it is cancelled. Keep the Task if the customer can press a stop button.
private var streamTask: Task<Void, Never>?
func start(_ input: String) {
streamTask = Task { await ask(input) }
}
func stop() {
streamTask?.cancel()
}
Cancelling closes the connection. The text received so far stays in your state, and the conversation keeps the messages that were completed. A cancelled stream ends with Swift's CancellationError, not with an OctoError.
Keep the UI responsive
- Update one piece of published state instead of rebuilding a list on every delta.
- Run the loop from a
@MainActortype. The SDK already does its network work off the main thread. - Disable the send button while a stream is running, or queue the next message until
.messageDone. - Keep the task in your view model, not in the view, so a redraw does not restart the request.
Under the hood
The SDK reads the same server-sent events as the REST API and maps message.delta, message.done, tool.call and error to StreamEvent. It stops at the [DONE] marker. If you need the raw format, see Streaming in the API reference.
Tip: Use
chatfor short, non-visual calls such as a background check, andstreamChatwhere a person watches the answer appear.