1
const postRouter = t.router({
  randomNumber: t.procedure.subscription(() => {
    return observable<{ randomNumber: number }>((emit) => {
      const timer = setInterval(() => {
        // emits a number every second
        emit.next({ randomNumber: Math.round(Math.random() * 10000) })
      }, 1000)

      return () => {
        clearInterval(timer)
      }
    })
  })
})

How would one call this subscription with an argument? Like if I only wanted it to emit if the random number was even or odd bases on an arg.

Thanks for any direction

boom
  • 10,856
  • 9
  • 43
  • 64

1 Answers1

2

You can achieve it like you do with query and mutation with input https://trpc.io/docs/server/procedures#input-validation

server side :

  randomNumber: t.procedure
    .input(z.object({ odd: z.boolean() }))
    .subscription(({ input }) => {
      return observable<{ randomNumber: number }>((emit) => {
        const timer = setInterval(() => {
          // emits a number every second
          let randomNumber = Math.round(Math.random() * 10000);
          if (
            (input.odd && randomNumber % 2 === 1) ||
            (!input.odd && randomNumber % 2 === 0)
          )
            randomNumber++;
          emit.next({ randomNumber });
        }, 1000);

        return () => {
          clearInterval(timer);
        };
      });
    }),

client side :

    client.randomNumber.subscribe({ odd: false }, {
      onData: (data) => {
        console.log(data);
      }
    });
eskan
  • 309
  • 1
  • 3
  • 13
  • how do you pass data to the server of that same websocket channel ? – Ahmed Eid Jun 04 '23 at 22:49
  • In this sample 'odd' with the value 'false' is the data pass to the server. On the same channel you can call query, mutation with args event if you use a WS. If you want to split calls (http vs WS) refer splitLink : https://trpc.io/docs/client/links/splitLink – eskan Jun 20 '23 at 09:17