Is it possible to cancel Graphql subscriptions?

Our team is mostly using “normal” request operations in Apollo, but are starting to use subscriptions for some long-running tasks (at the moment file-export).

Therefore a discussion started in our team; is it somehow possible for the client to cancel a subscription - so the apollo server can abort and clean up any expensive operations?

This could for example be the case if a user would initiate a file download, and then cancel?

2 Likes

@alexb the useSubscription hook will automatically unsubscribe any started subscriptions, when the component using it is unmounted. If you want manual control over when subscriptions are stopped, you’re better off using Apollo Client’s client.subscribe() method directly, like:

const observer = client.subscribe({
  query: SOME_SUBSCRIPTION,
  variables: {
    someId,
  },
});

const subscription = observer.subscribe(({ data }) => {
  console.log('data received', data);
  ...
});

...

// When you want to unsubscribe yourself, call
subscription.unsubscribe();

Good point (we are using svelte, but same principles apply). I’m more thinking about the server here. How can we notify the server that the subscription was cancelled?

1 Like

@alexb you shouldn’t need to do anything to notify the server, you should see the onDisconnect method in your subscriptions definition fire

@michael-watson correct me if I’m wrong, but is onDisconnect not when the socket itself is closed, and not when an individual subscription is cancelled?

Yes but I need to double check, I thought it would still fire for the cancel but I’m not sure if there is a way to tell that the closed socket is the cancelled one

Did you find a way to tell the server to cancel your one subscription?

No… We have not converted more to subscriptions, also because of this issue…

A similar issue was raised here: Problem in unsubscribe of useSubscription react hook · Issue #7964 · apollographql/apollo-client · GitHub

Did you find an answer for this question yet?