Unsubscribing stops receiving updates or messages you no longer want. It helps keep your data and notifications clean and relevant.
Unsubscribing in 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.
unsubscribe().// Start subscription const subscription = client.subscribe({ query: MY_SUBSCRIPTION }).subscribe({}); // Later, to unsubscribe subscription.unsubscribe();
const subscription = client.subscribe({ query: NEW_COMMENTS }).subscribe({}); // Stop receiving new comments subscription.unsubscribe();
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.
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);
Always unsubscribe when you no longer need updates to save bandwidth and resources.
Failing to unsubscribe can cause memory leaks or unwanted data processing.
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.
Practice
What does calling unsubscribe() on a GraphQL subscription do?
Solution
Step 1: Understand the purpose of unsubscribe()
Theunsubscribe()method is designed to stop live updates from a GraphQL subscription.Step 2: Differentiate from other actions
It does not restart, delete permanently, or pause the subscription; it simply stops updates.Final Answer:
It stops receiving live updates from the subscription. -> Option DQuick Check:
Unsubscribe() stops updates = D [OK]
- Thinking unsubscribe() restarts the subscription
- Confusing unsubscribe() with deleting the subscription
- Assuming unsubscribe() only pauses updates
Which of the following is the correct syntax to stop a GraphQL subscription stored in variable sub?
const sub = client.subscribe({ query: MY_SUBSCRIPTION });
// Stop subscription here
Solution
Step 1: Identify the unsubscribe method on subscription object
The subscription object returned byclient.subscribe()has anunsubscribe()method to stop it.Step 2: Match correct syntax
Callingsub.unsubscribe();correctly stops the subscription. Other options are invalid method calls.Final Answer:
sub.unsubscribe(); -> Option CQuick Check:
Call unsubscribe() on subscription object = A [OK]
- Using unsubscribe() as a standalone function
- Calling stop() instead of unsubscribe()
- Trying to unsubscribe via client object
Given the code below, what will be logged after sub.unsubscribe() is called?
const sub = client.subscribe({ query: MY_SUBSCRIPTION });
sub.subscribe({
next(data) { console.log('Received:', data); },
error(err) { console.error('Error:', err); }
});
sub.unsubscribe();
// Later, server sends new data
Solution
Step 1: Understand unsubscribe effect on subscription callbacks
Callingunsubscribe()stops the subscription and prevents furthernextcallbacks.Step 2: Predict logging behavior after unsubscribe
Since subscription is stopped, no new data triggersconsole.log, so no logs appear after unsubscribe.Final Answer:
No logs will appear after unsubscribe is called. -> Option BQuick Check:
Unsubscribe stops callbacks = C [OK]
- Expecting data logs after unsubscribe
- Assuming unsubscribe triggers an error
- Thinking one last data event logs after unsubscribe
Identify the error in the code below that prevents unsubscribing correctly:
const subscription = client.subscribe({ query: NEW_MESSAGES });
subscription.next({
next(data) { console.log(data); }
});
subscription.unsubscribe();
Solution
Step 1: Check subscription method usage
The subscription object usessubscribe()to listen for data, notnext().Step 2: Identify correct method to receive data
Replacingsubscription.next()withsubscription.subscribe()fixes the issue and allows unsubscribe to work properly.Final Answer:
Usingsubscription.next()instead ofsubscription.subscribe(). -> Option AQuick Check:
Use subscribe(), not next(), to listen = B [OK]
- Calling next() instead of subscribe()
- Unsubscribing before subscribing
- Ignoring error callback (not critical here)
You have multiple active subscriptions stored in an array subs. How do you efficiently unsubscribe from all of them?
const subs = [sub1, sub2, sub3];
// Your code here
Solution
Step 1: Understand unsubscribing multiple subscriptions
Each subscription object has anunsubscribe()method to stop it individually.Step 2: Use array iteration to call unsubscribe on each
Usingsubs.forEach(s => s.unsubscribe());calls unsubscribe on all subscriptions efficiently.Final Answer:
subs.forEach(s => s.unsubscribe()); -> Option AQuick Check:
Call unsubscribe() on each subscription in array = A [OK]
- Calling unsubscribe() on the array itself
- Using stop() method which does not exist
- Trying to call unsubscribe() without iteration
Ready to prove it?
Pass the test and this pattern moves unknown
