Sign up for Hasura Newsletter
Loading...

Create Subscription and Render Result

So let's define the graphql subscription to be used.

Open Todo/OnlineVC.swift and update following code,

githubTodo/OnlineVC.swift
+ var onlineUsersSub: Cancellable?
// Subscribe for Online users
private 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 users
private 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 users
private func subscribeOnlineUsers(){
onlineUsersSub = apollo.subscribe(subscription: GetOnlineUsersSubscription()) { (result, error) in
if((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.

Did you find this page helpful?
Start with GraphQL on Hasura for Free
  • ArrowBuild apps and APIs 10x faster
  • ArrowBuilt-in authorization and caching
  • Arrow8x more performant than hand-rolled APIs
Promo
footer illustration
Brand logo
© 2024 Hasura Inc. All rights reserved
Github
Titter
Discord
Facebook
Instagram
Youtube
Linkedin