Subscriptions


Subscriptions are long-lived GraphQL read operations that can update their response over time, enabling clients to receive new data as it becomes available.

Apollo iOS 2.0 supports subscriptions over HTTP, using chunked multipart responses

note
ApolloWebSocket support for 2.0 is coming soon. If you need to use web sockets, please continue using Apollo iOS 1.0 for now.

You must use whichever protocol is supported by your GraphQL endpoint.

Enabling support

To support GraphQL subscriptions, you need to initialize your ApolloClient instance with a NetworkTransport that supports subscriptions.

The default NetworkTransport for Apollo iOS is the RequestChainNetworkTransport. This transport supports subscriptions over HTTP, with no additional configuration required.

If you are building a custom network transport and want to support subscriptions, you may use the provided JSONResponseParser for parsing multi-part response data.

Generating and executing

Apollo iOS supports subscriptions via code generation. Similar to queries, subscriptions are represented by instances of generated classes, conforming to the GraphQLSubscription protocol.

GraphQL
ReviewAddedSubscription.graphql
1subscription ReviewAdded {
2  reviewAdded {
3    id
4    stars
5  }
6}

After you generate these classes, you can execute subscriptions using ApolloClient.subscribe(subscription:) with a subscription-supporting NetworkTransport. If you do, your client continues to receive updated data until the subscription is canceled or is terminated by the server.

Swift
1let subscription = try await client.subscribe(subscription: ReviewAddedSubscription())
2
3Task {
4  for try await result in subscription {
5    // Handle each update from the subscription.
6  }
7}

Note: GraphQL subscriptions are distinct from watching queries. A query watcher is only updated when new data is written to the local cache (usually by another network operation). A GraphQL subscription is a long-lived request that might receive updated data from the server continually.

Canceling a subscription

Apollo iOS 2.0 participates in Swift structured concurrency task cancellation for subscription cancellation. To cancel a subscription, you cancel the Task that the subscription was initiated in.

When a task is cancelled, the subscription's AsyncThrowingStream will terminate gracefully and the connection to the server will be closed.

Swift
1class ReviewViewController {
2
3  let client: ApolloClient!
4  private var subscriptionTask: Task<Void, Never>?
5
6  func subscribeToReviews() {
7    // Keep a reference to the subscription task
8    self.subscriptionTask = Task {
9      do {
10        let subscription = try await client.subscribe(subscription: ReviewAddedSubscription())
11
12        for try await result in subscription {
13          // Handle each update from the subscription
14          print("Received subscription update: \(result.data)")
15        }
16      } catch {
17        print("Subscription error: \(error)")
18      }
19    }
20  }
21
22  deinit {
23    // Cancel the subscription task when this object is deallocated
24    self.subscriptionTask?.cancel()
25  }
26}
Feedback

Edit on GitHub

Ask Community