실시간 데이터 구독 구현
tRPC 구독 절차를 만들어 서버에서 연결된 클라이언트로 실시간 업데이트를 전송합니다.
실시간 데이터 구독 구현은(는) CoddyKit의 무료 tRPC End-to-End Type Safe APIs 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 tRPC End-to-End Type Safe APIs 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. tRPC End-to-End Type Safe APIs 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Real-time Data with Subscriptions
Welcome to the final lesson on tRPC real-time! We've learned about WebSockets, now let's build live data features.
Subscriptions in tRPC allow your server to push real-time updates to connected clients. Unlike queries (which pull data) or mutations (which modify data), subscriptions are push-based.
- Queries: Client asks, server responds once.
- Mutations: Client sends data, server performs action, responds once.
- Subscriptions: Client asks once, server sends updates over time.
Defining Server Subscriptions
To create a subscription on your tRPC server, you use the createSubscription helper, similar to createQuery or createMutation.
A key difference is that a subscription procedure returns an observable. An observable is a stream of data that can emit multiple values over time.
Let's look at the basic structure.
The Observable Pattern
When defining a subscription, you'll use an observable pattern. This involves a function that receives an emit function and returns a cleanup function.
- The
emitfunction is what you call to send data to clients. - The cleanup function (returned by your subscription logic) runs when a client unsubscribes.
This allows you to manage resources like event listeners or intervals.
Server Code: Basic Live Counter
Here's a simple tRPC server-side subscription that emits a number every second. This number could represent anything, like a live user count.
import { router, publicProcedure } from './trpc';
import { observable } from '@trpc/server/observable';
export const appRouter = router({
onUpdate: publicProcedure.subscription(() => {
// This is where we create the observable
return observable<number>((emit) => {
let count = 0;
const interval = setInterval(() => {
count++;
emit.next(count); // Push new data to clients
}, 1000);
// Return a cleanup function
return () => {
clearInterval(interval);
};
});
}),
});
// This code is illustrative and not directly runnable
// without a full Node.js server setup.
// For context, 'router' and 'publicProcedure' would be
// initialized from '@trpc/server'.
Understanding the Server Flow
In the previous example:
publicProcedure.subscription(() => {...})defines the subscription endpoint.observablecreates a data stream that will send((emit) => {...}) numbertypes.emit.next(count)is called repeatedly insidesetIntervalto push the currentcountto all subscribed clients.- The returned function
() => { clearInterval(interval); }ensures the interval stops when a client disconnects or unsubscribes, preventing memory leaks.
Consuming Subscriptions on the Client
On the client-side, tRPC provides a convenient hook for consuming subscriptions, typically trpc.useSubscription if you're using React Query.
This hook works similarly to useQuery but maintains an open connection and updates your component whenever new data arrives from the server.
Client Code: React Component Example
Here's a React component that subscribes to our onUpdate procedure and displays the live counter. Notice how data updates automatically.
import React from 'react';
// Mock tRPC client for runnable example
const mockTRPCClient = {
onUpdate: {
subscribe: (opts) => {
let count = 0;
const interval = setInterval(() => {
count++;
opts.onData(count); // Simulate server pushing data
}, 1000);
return { // Return unsubscribe function
unsubscribe: () => clearInterval(interval),
};
},
},
};
// Mock useSubscription hook
const useSubscription = (path, input, { onData, onError }) => {
React.useEffect(() => {
const subscription = mockTRPCClient[path].subscribe({
onData,
onError,
});
return () => subscription.unsubscribe();
}, [path, input, onData, onError]);
};
function LiveCounter() {
const [currentCount, setCurrentCount] = React.useState(0);
useSubscription(
'onUpdate', // Path to your tRPC subscription
undefined, // No input for this subscription
{
onData(data) {
setCurrentCount(data); // Update state with new data
},
onError(err) {
console.error('Subscription error:', err);
},
}
);
return (
<div>
<h3>Live Counter:</h3>
<p>Current value: <b>{currentCount}</b></p>
</div>
);
}
// This would be rendered by a framework like React.
// For runnable purposes, we can simulate a main entry point.
export default function Main() {
return <LiveCounter />;
}
Subscriptions with Input
Just like queries and mutations, subscriptions can accept input. This is incredibly useful for filtering or customizing the data stream for each client.
For example, you might subscribe to updates for a specific productId or a particular chat roomName.
You'll define the input schema using Zod on the server and pass the input object on the client.
Code: Subscription with Input
Here's how you'd define a subscription that takes a topic string as input on the server, and how a client would use it.
/* --- SERVER-SIDE (Illustrative) --- */
import { z } from 'zod';
import { router, publicProcedure } from './trpc';
import { observable } from '@trpc/server/observable';
export const appRouterWithInput = router({
onTopicUpdate: publicProcedure
.input(z.object({ topic: z.string() })) // Define input schema
.subscription(({ input }) => {
return observable<string>((emit) => {
// Simulate updates for a specific topic
const interval = setInterval(() => {
emit.next(`Update for '${input.topic}': ${Date.now()}`);
}, 2000);
return () => clearInterval(interval);
});
}),
});
/* --- CLIENT-SIDE (React Component) --- */
import React from 'react';
// Mock tRPC client for runnable example
const mockTRPCClientWithInput = {
onTopicUpdate: {
subscribe: (input, opts) => {
const interval = setInterval(() => {
opts.onData(`Update for '${input.topic}': ${Date.now()}`);
}, 2000);
return {
unsubscribe: () => clearInterval(interval),
};
},
},
};
// Mock useSubscription hook for runnable example
const useSubscriptionWithInput = (path, input, { onData, onError }) => {
React.useEffect(() => {
const subscription = mockTRPCClientWithInput[path].subscribe(
input,
{ onData, onError }
);
return () => subscription.unsubscribe();
}, [path, input, onData, onError]);
};
function TopicUpdates({ topic }) {
const [latestUpdate, setLatestUpdate] = React.useState('');
useSubscriptionWithInput(
'onTopicUpdate',
{ topic }, // Pass the input object
{
onData(data) {
setLatestUpdate(data);
},
onError(err) {
console.error('Subscription error:', err);
},
}
);
return (
<div>
<h4>Topic: {topic}</h4>
<p>{latestUpdate}</p>
</div>
);
}
export default function Main() {
return (
<div>
<TopicUpdates topic="news" />
<TopicUpdates topic="sports" />
</div>
);
}
Best Practices for Subscriptions
When working with tRPC subscriptions, consider these best practices:
- Cleanup: Always return a cleanup function from your observable to release resources (e.g., clear intervals, close database connections).
- Error Handling: Implement
onErrorcallbacks on the client to gracefully handle subscription errors. - Rate Limiting: Be mindful of how frequently you emit data to avoid overwhelming clients or your server.
- When to Use: Subscriptions are great for truly real-time data. For less critical updates, traditional queries with polling or client-side caching might be sufficient.
- Authentication/Authorization: Use tRPC middleware to protect subscription procedures, ensuring only authorized users receive updates.
Quick Check: Subscription Basics
You've defined a tRPC subscription that emits a string every 5 seconds. Which part of the client-side useSubscription hook would you use to process each incoming string?
Recap: Live Data Subscriptions
In this lesson, you've learned to implement live data subscriptions with tRPC:
- Server-side: Define subscription procedures using
publicProcedure.subscriptionand return anobservable. - Observable Logic: Use the
emit.next()function to push data and return a cleanup function. - Client-side: Consume subscriptions using
trpc.useSubscription, providing anonDatacallback to handle incoming real-time updates. - Input: Pass arguments to subscriptions for filtered or customized data streams.
Congratulations! You can now build powerful real-time features with tRPC's end-to-end type safety.
자주 묻는 질문
“실시간 데이터 구독 구현” 강의는 무료인가요?
네 — “실시간 데이터 구독 구현” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 tRPC End-to-End Type Safe APIs 강의 전체를 잠금 해제할 수 있습니다. tRPC End-to-End Type Safe APIs 강의에는 총 4개의 강의가 포함되어 있습니다.
“실시간 데이터 구독 구현”에서 뭘 배우나요?
tRPC 구독 절차를 만들어 서버에서 연결된 클라이언트로 실시간 업데이트를 전송합니다. 브라우저에서 직접 실행하는 실습 코드로 tRPC End-to-End Type Safe APIs을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
tRPC End-to-End Type Safe APIs을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 tRPC End-to-End Type Safe APIs은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“실시간 데이터 구독 구현” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 tRPC End-to-End Type Safe APIs 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 tRPC End-to-End Type Safe APIs 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- tRPC 실시간 기능 소개
- 구독을 위한 WebSockets 설정
- 실시간 데이터 구독 구현
- 재연결과 구독 정리 처리