Event Iterator in oRPC Clients
An Event Iterator in oRPC behaves like an AsyncGenerator. Simply iterate over it and await each event.
Basic Usage
ts
const iterator = await client.streaming()
for await (const event of iterator) {
console.log(event.message)
}
Stopping the Stream Manually
Call .return()
on the iterator to gracefully end the stream.
ts
const iterator = await client.streaming()
setTimeout(async () => {
// Stop the stream after 1 second
await iterator.return()
}, 1000)
for await (const event of iterator) {
console.log(event.message)
}
Error Handling
INFO
Unlike traditional SSE, the Event Iterator does not automatically retry on error. To enable automatic retries, refer to the Client Retry Plugin.
ts
const iterator = await client.streaming()
try {
for await (const event of iterator) {
console.log(event.message)
}
}
catch (error) {
if (error instanceof ORPCError) {
// Handle the error here
}
}
INFO
Errors thrown by the server can be instances of ORPCError
.
Using consumeEventIterator
oRPC provides a utility function consumeEventIterator
to consume an event iterator with lifecycle callbacks.
ts
import { consumeEventIterator } from '@orpc/client'
const cancel = consumeEventIterator(client.streaming(), {
onEvent: (event) => {
console.log(event.message)
},
onError: (error) => {
console.error(error)
},
onSuccess: (value) => {
console.log(value)
},
onFinish: (state) => {
console.log(state)
},
})
setTimeout(async () => {
// Stop the stream after 1 second
await cancel()
}, 1000)
INFO
This utility accepts both promises and event iterators. Passing a promise directly lets it infer correct error type.