Subscribe to real-time events
Subscribe to mutations for creating real-time clients.
Because the lifetime of the subscription will last longer than the lifetime of a single function, you can create an instance variable at the top of your class:
1var subscription: GraphQLSubscriptionOperation<Todo>?
To listen to creation updates, you can use the following code sample:
1func createSubscription() {2 subscription = Amplify.API.subscribe(request: .subscription(of: Todo.self, type: .onCreate), valueListener: { (subscriptionEvent) in3 switch subscriptionEvent {4 case .connection(let subscriptionConnectionState):5 print("Subscription connect state is \(subscriptionConnectionState)")6 case .data(let result):7 switch result {8 case .success(let createdTodo):9 print("Successfully got todo from subscription: \(createdTodo)")10 case .failure(let error):11 print("Got failed result with \(error.errorDescription)")12 }13 }14 }) { result in15 switch result {16 case .success:17 print("Subscription has been closed successfully")18 case .failure(let apiError):19 print("Subscription has terminated with \(apiError)")20 }21 }22}
Unsubscribing from updates
Listener (iOS 11+)
To unsubscribe from updates, you can call cancel()
on the subscription
1func cancelSubscription() {2 // Cancel the subscription listener when you're finished with it3 subscription?.cancel()4}
Combine (iOS 13+)
With the Combine flavor of the subscribe()
API, you have the option of canceling just the downstream Combine subscriber, or the entire GraphQL subscription.
Calling cancel()
on the subscription will disconnect the subscription from the backend. Any downstream subscribers will also be cancelled. On the other hand, calling cancel()
on the Combine subscriber (e.g., the AnyCancellable
returned from sink()
will cause that Combine subscriber to stop receiving updates, but any other attached subscribers will continue to receive subscription data. For example:
1let subscription = Amplify.API.subscribe(...)2let allUpdates = subscription.subscriptionDataPublisher.sink(...)3let filteredUpdates = subscription.subscriptionDataPublisher.filter{...}.sink(...)4
5allUpdates.cancel() // subscription is still connected,6 // filteredUpdates will still receive data7
8subscription.cancel() // subscription is now disconnected9 // filteredUpdates will no longer receive data