Observe in real time
Observe model mutations in real time
You can subscribe to changes on your Models. This reacts dynamically to updates of data to the underlying Storage Engine, which could be the result of GraphQL Subscriptions as well as Queries or Mutations that run against the backing AppSync API if you are synchronizing with the cloud.
1// You must hold a reference to your subscription.2var postsSubscription: AmplifyAsyncThrowingSequence<MutationEvent>?3
4// Then in the body of your code, subscribe to the subscription5func subscribeToPosts() async {6 let postsSubscription = Amplify.DataStore.observe(Post.self)7 self.postsSubscription = postsSubscription8
9 do {10 for try await changes in postsSubscription {11 // handle incoming changes12 print("Subscription received mutation: \(changes)")13 }14 } catch {15 print("Subscription received error: \(error)")16 }17}18
19// Then, when you're finished observing, cancel the subscription20func unsubscribeFromPosts() {21 postsSubscription?.cancel()22}
1// In your type declaration, declare a cancellable to hold onto the subscription2var postsSubscription: AnyCancellable?3
4// Then in the body of your code, subscribe to the publisher5func subscribeToPosts() {6 postsSubscription = Amplify.Publisher.create(Amplify.DataStore.observe(Post.self))7 .sink {8 if case let .failure(error) = $0 {9 print("Subscription received error - \(error)")10 }11 }12 receiveValue: { changes in13 // handle incoming changes14 print("Subscription received mutation: \(changes)")15 }16}17
18// Then, when you're finished observing, cancel the subscription19func unsubscribeFromPosts() {20 postsSubscription?.cancel()21}
Observe query results in real-time
observeQuery(...)
returns an initial data set, similar to query(...)
, and also automatically subscribes to subsequent changes to the query.
The first snapshot returned from observeQuery
will contain the same results as calling query
directly on your Model - a collection of all the locally available records. Subsequent snapshots will be emitted as updates to the dataset and received in the local store.
While data is syncing from the cloud, snapshots will contain all of the items synced so far and an isSynced
status of false
. When the sync process is complete, a snapshot will be emitted with all the records in the local store and an isSynced
status of true
.
In addition to typical real-time use cases, observeQuery
can be used on app launch to show your customers an initial data set from the local store while new data is being synced from cloud.
observeQuery
also accepts the same predicates and sorting options as query
.
1// You must hold a reference to your subscription.2var postsSubscription: AmplifyAsyncThrowingSequence<DataStoreQuerySnapshot<Post>>?3
4// Subscribe5func subscribeToPosts() async {6 let post = Post.keys7 let postsSubscription = Amplify.DataStore.observeQuery(8 for: Post.self,9 where: post.title.beginsWith("post") && post.rating > 10.0,10 sort: .ascending(post.rating)11 )12 // hold onto your subscription13 self.postsSubscription = postsSubscription14 do {15 // observe new snapshots16 for try await querySnapshot in postsSubscription {17 print("[Snapshot] item count: \(querySnapshot.items.count), isSynced: \(querySnapshot.isSynced)")18 }19 } catch {20 print("Error: \(error)")21 }22}23
24// When you're finished observing, cancel the subscription25func unsubscribeFromPosts() {26 postsSubscription?.cancel()27}
1// In your type declaration, declare a cancellable to hold onto the subscription2var postsSubscription: AnyCancellable?3
4func subscribeToPosts() {5 let post = Post.keys6 self.postsSubscription = Amplify.Publisher.create(7 Amplify.DataStore.observeQuery(8 for: Post.self,9 where: post.title.beginsWith("post") && post.rating > 10.0,10 sort: .ascending(post.rating)11 )12 )13 .sink {14 if case .failure(let error) = $0 {15 print("Error \(error)")16 }17 } receiveValue: { querySnapshot in18 print("[Snapshot] item count: \(querySnapshot.items.count), isSynced: \(querySnapshot.isSynced)")19 }20}21
22// Then, when you're finished observing, cancel the subscription23func unsubscribeFromPosts() {24 postsSubscription?.cancel()25}