oRPC event iterators
A job runner. Each button starts a job with a regular oRPC call, and every job card streams its progress from an oRPC event iterator: an async generator on the server that yields one event per step and then returns. Start a few jobs at once to see the streams run side by side.
Opens the example in StackBlitz in a new tab. The first start installs packages and takes a few seconds.
import { useListener, useSubmit } from "@hyper-fetch/react";
import { useState } from "react";
import { realtime, sdk } from "./api";
type Job = { id: string; steps: number };
const JobCard = ({ job }: { job: Job }) => {
const [log, setLog] = useState<string[]>([]);
// The payload is the procedure input. Each job is its own stream.
const { data, extra, status, error, onEvent } = useListener(
realtime.job.onProgress.$listener.setPayload({ id: job.id }),
);
onEvent(({ data: event }) => {
// `at` is a Date: the oRPC serializer keeps rich types in every event.
setLog((current) => [`${event.at.toLocaleTimeString()} ${event.stage}`, ...current].slice(0, 4));
});
return (
<article>
<header className="toolbar">
<strong>{job.id}</strong>
<small className="muted" aria-busy={status === "starting"}>
{status} / event {extra?.id ?? "-"}
</small>
</header>
<progress value={data?.step ?? 0} max={job.steps} />
{status === "ended" && <p>Done in {job.steps} steps.</p>}
{status === "failed" && <p className="error">{error?.message}</p>}
<ul className="log">
{log.map((line) => (
<li key={line}>{line}</li>
))}
</ul>
</article>
);
};
export const App = () => {
const [jobs, setJobs] = useState<Job[]>([]);
const { submit, submitting, error } = useSubmit(sdk.job.start.$mutation);
const start = async (steps: number) => {
const { data } = await submit({ payload: { steps } });
if (data) setJobs((current) => [data, ...current]);
};
return (
<main className="container">
<hgroup>
<h1>oRPC event iterators</h1>
<p>Each job streams its progress from an async generator on the server into useListener.</p>
</hgroup>
<div role="group">
{[4, 8, 12].map((steps) => (
<button key={steps} type="button" aria-busy={submitting} disabled={submitting} onClick={() => start(steps)}>
Start a {steps}-step job
</button>
))}
</div>
{error && <p className="error">Could not start the job: {error.message}</p>}
{jobs.length === 0 && <p className="muted">Start a job, or a few at once.</p>}
<div className="grid-2">
{jobs.map((job) => (
<JobCard key={job.id} job={job} />
))}
</div>
</main>
);
};
npx tiged BetterTyped/hyper-fetch/examples/orpc/event-iterator hyper-fetch-orpc-event-iterator && cd hyper-fetch-orpc-event-iterator && npm install && npm run devOrpcStreamAdapterconnects a HyperFetchSocketto oRPC event iterator procedures over an HTTP event stream.OrpcSocketSchema<typeof router>turns every event iterator into a typed$listener.useListenerstatus follows the stream:starting,listening, andendedwhen the generator returns.- Event meta:
withEventMeta(event, { id })on the server becomesextra.idon the client. - Rich types in events:
atis aDatein every event, encoded by the oRPC serializer.
How it works
-
server/router.tshas two procedures.job.startis a regular procedure that returns{ id, steps }.job.onProgressuses an async generator as its handler, which makes it an event iterator: eachyieldsends one event, and the end of the function ends the stream. -
Every event is wrapped in
withEventMeta(event, { id: String(step) }). After a reconnect the adapter sends that id back, oRPC passes it to the handler aslastEventId, and the loop continues from the next step. -
server/app.tsmounts the router with the fetchRPCHandlerin Hono. The same handler answers the regular call and the event stream. -
src/api.tscreates a client withOrpcAdapter()forjob.startand a socket withOrpcStreamAdapter()forjob.onProgress.OrpcSchemaleaves event iterators out andOrpcSocketSchemakeeps only them, so each SDK shows only what its transport can call.export const socket = new Socket({ url, adapter: OrpcStreamAdapter() });export const realtime = createSocketSdk<typeof socket, OrpcSocketSchema<typeof router>>(socket, {camelCaseToKebabCase: false,}); -
Appstarts a job withuseSubmit(sdk.job.start.$mutation)and renders aJobCardfor it. The card callsuseListener(realtime.job.onProgress.$listener.setPayload({ id: job.id })), which sendsPOST /api/rpc/job/onProgressand reads thetext/event-streamanswer. -
dataholds the latest event, so<progress value={data?.step}>moves with the stream.onEventkeeps a short log, formattingevent.atwithtoLocaleTimeString()because it is already aDate. When the generator returns,statusbecomesendedand the card shows "Done".
- Progress of long jobs: builds, imports, exports, AI responses.
- Live data on an oRPC API that already runs over HTTP, behind proxies or in serverless functions.
- For many streams per client over one connection, switch the socket to
OrpcWebsocketAdapterwith the WebSocketRPCHandler; the listeners stay the same.
Related
An async generator on the oRPC server is a stream of typed events. OrpcStreamAdapter and OrpcSocketSchema turn it
into a listener, and useListener shows each event, the event id and the end of the stream.
