处理重新连接与订阅清理
通过处理连接断开、自动重新连接和适当清理,让 tRPC 订阅达到生产环境要求。
处理重新连接与订阅清理 是 CoddyKit 上的免费 tRPC End-to-End Type Safe APIs 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 tRPC End-to-End Type Safe APIs 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 tRPC End-to-End Type Safe APIs 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Real-time Is Unreliable
You can set up subscriptions, but networks drop, servers restart, and tabs sleep. Production real-time code must handle disconnects and cleanup gracefully.
The wsLink and Reconnection
tRPC clients use a WebSocket client that can automatically reconnect when a connection is lost.
import { createWSClient, wsLink } from "@trpc/client";
const wsClient = createWSClient({
url: "ws://localhost:3000",
retryDelayMs: (attempt) => Math.min(1000 * attempt, 5000),
});Backoff Strategy
Reconnect attempts should use exponential backoff so a downed server is not hammered by every client at once.
Subscription Lifecycle
A subscription exposes lifecycle callbacks: data, error, started, and stopped.
trpc.onMessage.subscribe(undefined, {
onData: (msg) => add(msg),
onError: (err) => console.error(err),
onStarted: () => console.log("live"),
});Cleaning Up on Unmount
Every subscription returns an unsubscribe handle. Call it when the component unmounts to free resources.
const sub = trpc.onMessage.subscribe(undefined, { onData });
// later
sub.unsubscribe();React Cleanup Pattern
In React, return the cleanup from useEffect so it runs on unmount.
useEffect(() => {
const sub = trpc.onMessage.subscribe(undefined, { onData });
return () => sub.unsubscribe();
}, []);Server-Side Cleanup
On the server, the subscription generator must release resources when the client disconnects.
onMessage: publicProcedure.subscription(async function* (opts) {
const queue = subscribe();
try {
for await (const msg of queue) yield msg;
} finally {
queue.close(); // cleanup on disconnect
}
})Detecting Missed Events
After a reconnect, the client may have missed events. Track a last-seen id and refetch the gap on reconnect.
onStarted: () => {
fetchMissedSince(lastSeenId);
}Heartbeats and Timeouts
Heartbeat pings detect a silently dead connection so the client can trigger a reconnect instead of waiting forever.
Avoiding Memory Leaks
Forgetting to unsubscribe leaks listeners and slowly degrades both client and server. Always pair every subscribe with an unsubscribe.
Showing Connection Status
Surface the connection state in the UI so users know when data is live versus reconnecting, improving trust in real-time views.
wsClient.connectionState; // "connecting" | "open" | "closed"Quick Check
Test your subscription reliability knowledge.
Recap
You made subscriptions production-ready:
- Use the WS client with exponential backoff reconnection
- Always unsubscribe on unmount to avoid leaks
- Clean up server-side generators and refetch missed events
Robust reconnection and cleanup keep real-time apps reliable in the real world.
常见问题解答
「处理重新连接与订阅清理」课时是免费的吗?
是的 — 「处理重新连接与订阅清理」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 tRPC End-to-End Type Safe APIs 课程的其余内容,请升级到 CoddyKit PRO。 tRPC End-to-End Type Safe APIs 课程共包含 4 节课。
「处理重新连接与订阅清理」这节课中我会学到什么?
通过处理连接断开、自动重新连接和适当清理,让 tRPC 订阅达到生产环境要求。 你通过在浏览器中直接运行的动手代码来练习 tRPC End-to-End Type Safe APIs,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 tRPC End-to-End Type Safe APIs 需要有经验吗?
无需任何先前经验。CoddyKit 上的 tRPC End-to-End Type Safe APIs 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「处理重新连接与订阅清理」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 tRPC End-to-End Type Safe APIs 课中编写并运行代码吗?
能。每节 tRPC End-to-End Type Safe APIs 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- tRPC 实时通信简介
- 设置用于订阅的 WebSockets
- 实现实时数据订阅
- 处理重新连接与订阅清理