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: AmplifyAsyncThrowingSequence<GraphQLSubscriptionEvent<Todo>>
1var subscription: AnyCancellable?
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))3 Task {4 do {5 for try await subscriptionEvent in subscription {6 switch subscriptionEvent {7 case .connection(let subscriptionConnectionState):8 print("Subscription connect state is \(subscriptionConnectionState)")9 case .data(let result):10 switch result {11 case .success(let createdTodo):12 print("Successfully got todo from subscription: \(createdTodo)")13 case .failure(let error):14 print("Got failed result with \(error.errorDescription)")15 }16 }17 }18 } catch {19 print("Subscription has terminated with \(error)")20 }21 }22}
1func createSubscription() {2 let sequence = Amplify.API.subscribe(request: .subscription(of: Todo.self, type: .onCreate))3 subscription = Amplify.Publisher.create(sequence)4 .sink {5 if case let .failure(apiError) = $0 {6 print("Subscription has terminated with \(apiError)")7 } else {8 print("Subscription has been closed successfully")9 }10 }11 receiveValue: { result in12 switch result {13 case .connection(let subscriptionConnectionState):14 print("Subscription connect state is \(subscriptionConnectionState)")15 case .data(let result):16 switch result {17 case .success(let createdTodo):18 print("Successfully got todo from subscription: \(createdTodo)")19 case .failure(let error):20 print("Got failed result with \(error.errorDescription)")21 }22 }23 }24}
Unsubscribing from updates
Async/Await
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
Calling cancel()
on the sequence will disconnect the subscription from the backend. Any downstream subscribers will also be cancelled.
1let sequence = Amplify.API.subscribe(...)2let subscription = Amplify.Publisher.create(sequence)3let allUpdates = subscription.sink(...)4let filteredUpdates = subscription.filter{...}.sink(...)5sequence.cancel() // sequence is now disconnected6 // allUpdates and filteredUpdates will no longer receive data
Similarly, calling cancel()
on the Combine subscriber (e.g., the AnyCancellable
returned from sink()
) will cause the underlying sequence to cancel. This will cause all attached subscribers to stop receiving updates.
1allUpdates.cancel() // sequence is disconnected2 // filteredUpdates will no longer receive data