Read more about how data synchronization works in Syncing Data.

Start Sync

Ensure the sync process remains active throughout your app’s lifecycle by starting the sync process (startSync) in the top-most scope of your code.

To initiate the sync process:

try! ditto.startSync()

Subscriptions

With a subscription query, you can declaratively describe the data that you want a particular device to receive. When a query is subscribed, Ditto continuously syncs relevant documents that match the query to the local device.

The subscription query represents “what you want other peers to send you.” It is not a query that you run against the local database, but rather a query that you run against the remote peers to receive updates about documents that match the query.

Creating Subscriptions

The following snippet demonstrates how to establish a subscription to sync updates to documents in the cars collection with a field of color set to the value blue:

ditto.sync.registerSubscription("SELECT * FROM cars")

Sync subscriptions also support argument injection using the :argument syntax in DQL:

ditto.sync.registerSubscription("""
  SELECT *
  FROM cars
  WHERE color = :color
  """,
  [ "color": "blue" ])

Retrieving Subscriptions

Retrieve active sync subscriptions by calling the subscriptions method on the ditto.sync namespace:

let activeSubscriptions = ditto.sync.subscriptions;

Canceling Subscriptions

To cancel a subscription, call cancel on its subscription object you instantiated when setting up your subscription.

subscription.cancel()

Check if a sync subscription is canceled by using the isCancelled field on the subscription object:

subscription.isCancelled

Stopping Sync

To stop the sync process, call the stopSync function. Once called, you will be disconnect from any peers and all active sync subscriptions will be paused.

try! ditto.stopSync()