0
0
GraphQLquery~5 mins

Unsubscribing in GraphQL

Choose your learning style9 modes available
Introduction

Unsubscribing stops receiving updates or messages you no longer want. It helps keep your data and notifications clean and relevant.

You no longer want to get live updates about a chat or news feed.
You want to stop receiving notifications from a specific topic or event.
You want to save resources by stopping unnecessary data flow.
You want to clean up your active subscriptions to avoid confusion.
You want to control what information your app listens to.
Syntax
GraphQL
subscription MySubscription {
  newMessages {
    id
    content
  }
}

// To unsubscribe, call the unsubscribe method on the subscription object returned by the client.

GraphQL subscriptions are usually started via a client method that returns a subscription object.

To stop receiving updates, you call unsubscribe() on that subscription object.

Examples
This example shows starting a subscription and then stopping it by calling unsubscribe().
GraphQL
// Start subscription
const subscription = client.subscribe({ query: MY_SUBSCRIPTION }).subscribe({});

// Later, to unsubscribe
subscription.unsubscribe();
Unsubscribing stops the flow of new comment data.
GraphQL
const subscription = client.subscribe({ query: NEW_COMMENTS }).subscribe({});

// Stop receiving new comments
subscription.unsubscribe();
Sample Program

This code starts a GraphQL subscription to listen for new messages. It prints each new message received. After 5 seconds, it stops the subscription to stop receiving updates.

GraphQL
const { ApolloClient, InMemoryCache, gql } = require('@apollo/client/core');
const { WebSocketLink } = require('@apollo/client/link/ws');
const ws = require('ws');

const link = new WebSocketLink({
  uri: 'ws://localhost:4000/graphql',
  options: { reconnect: true },
  webSocketImpl: ws
});

const client = new ApolloClient({
  link,
  cache: new InMemoryCache()
});

const NEW_MESSAGES = gql`
  subscription {
    newMessages {
      id
      content
    }
  }
`;

const subscription = client.subscribe({ query: NEW_MESSAGES }).subscribe({
  next(data) {
    console.log('New message:', data.data.newMessages);
  },
  error(err) {
    console.error('Subscription error:', err);
  }
});

// Unsubscribe after 5 seconds
setTimeout(() => {
  subscription.unsubscribe();
  console.log('Unsubscribed from newMessages');
}, 5000);
OutputSuccess
Important Notes

Always unsubscribe when you no longer need updates to save bandwidth and resources.

Failing to unsubscribe can cause memory leaks or unwanted data processing.

Summary

Unsubscribing stops live updates from a GraphQL subscription.

Call unsubscribe() on the subscription object to stop.

This keeps your app efficient and avoids unwanted data.