Skip to content

Instantly share code, notes, and snippets.

@abeymm
Last active March 18, 2021 02:50
Show Gist options
  • Save abeymm/4efc1e345d376f9e92a6b1a94f3d94ba to your computer and use it in GitHub Desktop.
Save abeymm/4efc1e345d376f9e92a6b1a94f3d94ba to your computer and use it in GitHub Desktop.
Amplify Subscription with filters for iOS
import Amplify
import AmplifyPlugins
class SubscriptionManager {
static var subscription: GraphQLSubscriptionOperation<JSONValue>?
static func createSubscription(courseId: String) {
subscription = Amplify.API.subscribe (request: GraphQLRequest<JSONValue>.subscribeToCourseNotes(byCourseId: courseId),
valueListener: { subscriptionEvent in
switch subscriptionEvent {
case .connection(let connectionState):
print("connection state:", connectionState)
case .data(let data):
switch data {
case .success(let json):
do {
if let noteJSON = json.value(at: "subscribeToCourseNotes") {
let noteData = try JSONEncoder().encode(noteJSON)
let note = try JSONDecoder().decode(Note.self, from: noteData)
updateCourseWithNote(note: note)
} else {
fallbackRefresh(error: nil, courseId: courseId) // fallback to refresh the entire course
}
} catch(let error) {
fallbackRefresh(error: error, courseId: courseId)
}
case .failure(let error):
fallbackRefresh(error: error, courseId: courseId)
}
}
},
completionListener: { result in
switch result {
case .success:
print("Subscription has been closed successfully")
case .failure(let error):
ErrorHandler.handleError(error: error, showUser: false)
}
}
)
}
static func cancelSubscription() {
// Cancel the subscription listener when you're finished with it
subscription?.cancel();
}
}
extension GraphQLRequest {
static func subscribeToCourseNotes(byCourseId courseId: String) -> GraphQLRequest<JSONValue> {
let document = """
subscription subscribeToCourseNotes($courseId: ID!) {
subscribeToCourseNotes(courseId: $courseId) {
id
body
updatedAt
user {
id
name
}
}
}
"""
return GraphQLRequest<JSONValue>(document: document,
variables: ["courseId": courseId],
responseType: JSONValue.self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment