Amplify has re-imagined the way frontend developers build fullstack applications. Develop and deploy without the hassle.

Page updated Apr 29, 2024

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:

var subscription: AmplifyAsyncThrowingSequence<GraphQLSubscriptionEvent<Todo>>
var subscription: AnyCancellable?

To listen to creation updates, you can use the following code sample:

func createSubscription() {
subscription = Amplify.API.subscribe(request: .subscription(of: Todo.self, type: .onCreate))
Task {
do {
for try await subscriptionEvent in subscription {
switch subscriptionEvent {
case .connection(let subscriptionConnectionState):
print("Subscription connect state is \(subscriptionConnectionState)")
case .data(let result):
switch result {
case .success(let createdTodo):
print("Successfully got todo from subscription: \(createdTodo)")
case .failure(let error):
print("Got failed result with \(error.errorDescription)")
}
}
}
} catch {
print("Subscription has terminated with \(error)")
}
}
}
func createSubscription() {
let sequence = Amplify.API.subscribe(request: .subscription(of: Todo.self, type: .onCreate))
subscription = Amplify.Publisher.create(sequence)
.sink {
if case let .failure(apiError) = $0 {
print("Subscription has terminated with \(apiError)")
} else {
print("Subscription has been closed successfully")
}
}
receiveValue: { result in
switch result {
case .connection(let subscriptionConnectionState):
print("Subscription connect state is \(subscriptionConnectionState)")
case .data(let result):
switch result {
case .success(let createdTodo):
print("Successfully got todo from subscription: \(createdTodo)")
case .failure(let error):
print("Got failed result with \(error.errorDescription)")
}
}
}
}

Unsubscribing from updates

Async/Await

To unsubscribe from updates, you can call cancel() on the subscription.

func cancelSubscription() {
// Cancel the subscription listener when you're finished with it
subscription?.cancel()
}

Combine

Calling cancel() on the sequence will disconnect the subscription from the backend. Any downstream subscribers will also be cancelled.

let sequence = Amplify.API.subscribe(...)
let subscription = Amplify.Publisher.create(sequence)
let allUpdates = subscription.sink(...)
let filteredUpdates = subscription.filter{...}.sink(...)
sequence.cancel() // sequence is now disconnected
// 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.

allUpdates.cancel() // sequence is disconnected
// filteredUpdates will no longer receive data