DEV Community

loading...

Simple Todo - Part 5 of 6

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

If you prefer to make changes in the local database while the device is offline, and would like these changes to be synced automatically to the server (once the network connection is back live), then we need to set up Sync Engine.

Screenshot

On top of our previous implementation, we only need to add a single line of code (we will use one common GQLSync instance for all syncing actions).

let gqlsync = GQLSync(gqlserver)
Enter fullscreen mode Exit fullscreen mode

Whenever we make any changes in the local database we just need to forward these change requests to the Sync Engine, so it can do the job (keeping the Server synced) silently for us.

func createTodo(_ title: String) {

  let todo = Todo()
  todo.title = title
  todo.insert(gqldb)

  let variables = ["object": todo.values()]
  gqlsync.lazy("CreateTodo", variables, todo.objectId)
}
Enter fullscreen mode Exit fullscreen mode
func completeTodo(_ todo: Todo) {

  todo.completed = true
  todo.updatedAt = Date()
  todo.update(gqldb)

  let variables = ["object": todo.values()]
  gqlsync.lazy("UpdateTodo", variables, todo.objectId)
}
Enter fullscreen mode Exit fullscreen mode

And pretty much that's all we need for keeping the local database changes synced automatically. You can check the full source code here.

Discussion (0)