@@ -349,18 +349,18 @@ export class MyService extends TypedEventEmitter<MyServiceEvents> {
349349
350350### 3. Create Subscriptions in Router
351351
352- Use a helper to reduce boilerplate . For global events (broadcast to all subscribers):
352+ Use ` toIterable() ` on the service to convert events to an async iterable . For global events (broadcast to all subscribers):
353353
354354``` typescript
355355// src/main/trpc/routers/my-router.ts
356- import { on } from " node:events" ;
357356import { MyServiceEvent , type MyServiceEvents } from " ../../services/my-service/schemas" ;
358357
359358function subscribe<K extends keyof MyServiceEvents >(event : K ) {
360359 return publicProcedure .subscription (async function * (opts ) {
361360 const service = getService ();
362- for await (const [payload] of on (service , event , { signal: opts .signal })) {
363- yield payload as MyServiceEvents [K ];
361+ const iterable = service .toIterable (event , { signal: opts .signal });
362+ for await (const data of iterable ) {
363+ yield data ;
364364 }
365365 });
366366}
@@ -382,15 +382,15 @@ export interface ShellEvents {
382382}
383383
384384// Router filters events to the specific session
385- function subscribeToSession <K extends keyof ShellEvents >(event : K ) {
385+ function subscribeFiltered <K extends keyof ShellEvents >(event : K ) {
386386 return publicProcedure
387387 .input (sessionIdInput )
388388 .subscription (async function * (opts ) {
389389 const service = getService ();
390390 const targetSessionId = opts .input .sessionId ;
391+ const iterable = service .toIterable (event , { signal: opts .signal });
391392
392- for await (const [payload] of on (service , event , { signal: opts .signal })) {
393- const data = payload as ShellEvents [K ];
393+ for await (const data of iterable ) {
394394 if (data .sessionId === targetSessionId ) {
395395 yield data ;
396396 }
@@ -399,8 +399,8 @@ function subscribeToSession<K extends keyof ShellEvents>(event: K) {
399399}
400400
401401export const shellRouter = router ({
402- onData: subscribeToSession (ShellEvent .Data ),
403- onExit: subscribeToSession (ShellEvent .Exit ),
402+ onData: subscribeFiltered (ShellEvent .Data ),
403+ onExit: subscribeFiltered (ShellEvent .Exit ),
404404});
405405```
406406
0 commit comments