RealmSync class

Real-time bidirectional sync engine between Realm database and MongoDB Atlas.

This is the main entry point for sync functionality. It manages multiple collections, handles conflict resolution, coordinates with the server via Socket.IO, and provides a unified stream of all sync events.

Quick Start

// 1. Initialize Realm with sync models
final realm = Realm(Configuration.local([
  ChatMessage.schema,
  SyncMetadata.schema,
  SyncDBCache.schema,
  SyncOutboxPatch.schema,
]));

// 2. Connect Socket.IO
final socket = IO.io('http://your-server:3000', ...);
socket.connect();

// 3. Create RealmSync instance
final realmSync = RealmSync(
  realm: realm,
  socket: socket,
  userId: 'user-123',
  configs: [
    SyncCollectionConfig<ChatMessage>(
      results: realm.all<ChatMessage>(),
      collectionName: 'chat_messages',
      idSelector: (obj) => obj.id,
      needsSync: (obj) => obj.syncUpdateDb,
    ),
  ],
);

// 4. Start syncing
realmSync.start();

// 5. Write data with sync
realm.writeWithSync(message, () {
  message.text = "Hello!";
  message.syncUpdateDb = true;
});
realmSync.syncObject('chat_messages', message.id);

Features

  • Automatic Conflict Resolution: Last-write-wins based on UTC timestamps
  • Offline Support: Changes queue locally and sync when online
  • Batch Operations: Intelligent batching reduces network overhead
  • Historic Sync: Catch up on missed changes after being offline
  • Change Stream: Monitor all sync events via changes stream
  • Manual Sync: Force sync specific objects with syncObject()

Important Notes

  • userId is required for security and multi-user isolation
  • Include sync models in Realm config: SyncMetadata, SyncDBCache, SyncOutboxPatch
  • Set sync_updated_at timestamps using writeWithSync() helper
  • Call start() after construction to begin syncing
  • Call dispose() when done to cleanup resources
Available extensions

Constructors

RealmSync({required dynamic realm, required Socket socket, required String userId, required List<SyncCollectionConfig> configs})

Properties

changes Stream<SyncObjectEvent>
Stream of all sync events across all collections.
no setter
configs List<SyncCollectionConfig>
List of collection configurations defining what and how to sync.
final
hashCode int
The hash code for this object.
no setterinherited
realm → dynamic
The Realm database instance containing collections to sync.
final
runtimeType Type
A representation of the runtime type of the object.
no setterinherited
socket → Socket
Socket.IO connection to the sync server.
final
userId String
Unique identifier for the current user.
final

Methods

dispose() → void
Clean up all resources and stop syncing.
fetchAllHistoricChanges({Map<String, int>? sinceOverrides, int limit = 500, bool applyLocally = true, bool skipEmptyCollections = false}) Future<Map<String, HistoricChangesResult>>

Available on RealmSync, provided by the RealmSyncHistoricExtension extension

Fetch historic changes for ALL configured collections.
fetchHistoricChanges(String collectionName, {int? since, int limit = 500, String? filterExpr, List? args, bool applyLocally = true}) Future<HistoricChangesResult>

Available on RealmSync, provided by the RealmSyncHistoricExtension extension

Fetch (and optionally apply) historic changes for a collection using the server's sync:get_changes endpoint.
lastRemoteTimestamp(String collectionName) int
Get the last remote timestamp for a collection.
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
start() → void
Start the sync engine and begin synchronizing all configured collections.
subscribe(String collectionName, {required String filterExpr, List args = const []}) → void
Subscribe to server-side filtered updates for a collection.
syncObject(String collectionName, String objectId) → void
Manually trigger immediate sync for a specific object.
syncObjects(String collectionName, List<String> objectIds) → void
Manually trigger sync for multiple objects in a collection.
toString() String
A string representation of this object.
inherited
unsubscribe(String collectionName) → void
Unsubscribe from server-side filtered updates for a collection.

Operators

operator ==(Object other) bool
The equality operator.
inherited