-
I'm creating a subscription that will continuously push data to the client. This is basically an endless loop as data will be coming into the system, whether a client is listening or not. On the backend resources are needed to make this work. How can I know, server-side, that the client is no longer listening to the subscription? For instance, the connection was terminated or I believe there is also an unsubscribe method in most client. I would need this to tear down the processing that is happening and avoid the server from eventually running out of resources. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
Here is an example of tearing down an example after the client disconnected. https://codesandbox.io/s/regression-subscription-not-closed-d8d5mj?file=/index.ts import { createServer, Repeater } from "@graphql-yoga/node";
const server = createServer({
schema: {
typeDefs: /* GraphQL */ `
type Query {
hello: String
}
type Subscription {
currentDate: String
}
`,
resolvers: {
Query: {
hello: () => "Hello from Yoga!"
},
Subscription: {
currentDate: {
resolve: (value) => value,
subscribe: () =>
new Repeater(async (next, stop) => {
console.log("Subscription starts");
const interval = setInterval(() => {
console.log("next");
next(new Date().toString());
}, 1000).unref();
stop.then(() => {
console.log("Subscription ends");
clearInterval(interval);
});
await stop;
})
}
}
}
}
});
server.start(); PLEASE NOTE that we are currently having a regression on the latest GraphQL Yoga version, that does not properly cleanup subscriptions. We are working on fixing it (#1399). |
Beta Was this translation helpful? Give feedback.
Here is an example of tearing down an example after the client disconnected. https://codesandbox.io/s/regression-subscription-not-closed-d8d5mj?file=/index.ts