DEV Community

loading...

Simple Todo - Part 4 of 6

Related Code
Mobile Application Development. Scalable Architecture Design. Custom Backend Development. Application Security. Performance Engineering. Analytics. Maintenance.
・1 min read

As a follow-up to our previous implementation, we will add the subscription functionality to our existing demo app.

Let's extend the appsync.graphql file with the necessary Subscriptions.

Screenshot

We will fetch the todo items and initiate the subscriptions whenever the app became active.

func initObservers() {

  fetchTodos()

  if (callbackIdCreate == nil) {
    callbackIdCreate = subscribe("OnCreateTodo")
  }
  if (callbackIdUpdate == nil) {
    callbackIdUpdate = subscribe("OnUpdateTodo")
  }
}
Enter fullscreen mode Exit fullscreen mode
func subscribe(_ queryName: String) -> String? {

  let query = GQLQuery[queryName]

  let callbackId = gqlserver.subscription(query, [:]) { result, error in
    if let error = error {
      print(error.localizedDescription)
    } else {
      if let values = result.values.first as? [String: Any] {
        self.updateDatabase(values)
      }
    }
  }
  return callbackId
}
Enter fullscreen mode Exit fullscreen mode

And we will unsubscribe from the subscriptions whenever the app resigns active.

func stopObservers() {

  if (callbackIdCreate != nil) {
    unsubscribe(callbackIdCreate)
    callbackIdCreate = nil
  }
  if (callbackIdUpdate != nil) {
    unsubscribe(callbackIdUpdate)
    callbackIdUpdate = nil
  }
}
Enter fullscreen mode Exit fullscreen mode
func unsubscribe(_ callbackId: String?) {

  if let callbackId = callbackId {
    gqlserver.subscription(cancel: callbackId) { error in
      if let error = error {
        print(error.localizedDescription)
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

With these code extensions, the device's local database (and the user interface) will be updated automatically by the server-side changes. You can check the full source code here.

Discussion (0)