Create Subscription and Render Result
So let's define the graphql subscription to be used.
Open Todo/OnlineVC.swift
and update following code,
+ var onlineUsersSub: Cancellable?// Subscribe for Online usersprivate func subscribeOnlineUsers(){+ onlineUsersSub = apollo.subscribe(subscription: GetOnlineUsersSubscription()) { (result, error) in+ if((error) != nil) { dump(error); return }+ }registerSelfAsOnlineTimer = Timer.scheduledTimer(timeInterval: 30, target: self, selector: #selector(updateLastSeenMutationCloud), userInfo: nil, repeats: true)registerSelfAsOnlineTimer?.fire()}// Un-subscribe for online usersprivate func unSubscribeOnlineUsers(){+ onlineUsersSub?.cancel()registerSelfAsOnlineTimer?.invalidate()}
We are creating a Cancellable
variable, and the assing apollo.subscribe graphql subscription we defined above to fetch the online user data.
Now, we will update the UI with the results from this subscription. Update the following in the subscribeOnlineUsers
function:
// Subscribe for Online usersprivate func subscribeOnlineUsers(){onlineUsersSub = apollo.subscribe(subscription: GetOnlineUsersSubscription()) { (result, error) inif((error) != nil) { dump(error); return }guard let data = result?.data else { return }+ self.onlineUsers = data.onlineUsers.compactMap{$0.user?.name}+ DispatchQueue.main.async {+ self.onlineUserCount.text = String(self.onlineUsers.count)+ self.onlineUsersTable.reloadData()+ self.setupUI()+ }}
Now that we have the real data, let's remove the mock online users in onlineUsers
variable
- var onlineUsers: [String] = ["Loki", "Thor", "Dr Strange", "Hulk", "Mantis", "TChala", "Iron Man", "Thanos"]+ var onlineUsers: [String] = []
How does this work?
We are using the Apollo.subscribe#subscription
which gives cancellable with GraphQLResultSet (similar to query
and mutation
). The result
object gives the result of the realtime data for the query we have made.
Re-run your ios app and see yourself online! Don't be surprised; There could be other users online as well.
Awesome! You have completed implementations of a GraphQL Query, Mutation and Subscriptions.
- Build apps and APIs 10x faster
- Built-in authorization and caching
- 8x more performant than hand-rolled APIs