deleteWithSync<T extends dynamic> method

void deleteWithSync<T extends dynamic>(
  1. T obj, {
  2. required String userId,
  3. required String collectionName,
})

Deletes an object and creates a DBCache entry to track the deletion for syncing with the server.

Usage:

realm.deleteWithSync(
  goal,
  userId: 'user-123',
  collectionName: 'goals',
);

Implementation

void deleteWithSync<T extends RealmObject>(
  T obj, {
  required String userId,
  required String collectionName,
}) {
  write(() {
    // Capture state before deletion and serialize immediately
    // to avoid RealmList references becoming invalid after deletion
    String? serializedData;
    String? entityId;

    try {
      final json = RealmJson.toJsonWith(obj, null);
      // Serialize immediately while object is still valid
      // This deep-copies the data and avoids holding RealmList references
      serializedData = jsonEncode(canonicalizeMap(json));
      entityId = _extractEntityId(obj);
    } catch (e) {
      // Continue with deletion even if we can't capture state
    }

    // Delete the object
    delete(obj);

    // Create DBCache entry for deletion tracking
    if (entityId != null && serializedData != null) {
      try {
        final key = '$userId|$collectionName|$entityId';
        final dbCache = SyncDBCache(
          key,
          userId,
          collectionName,
          entityId,
          jsonEncode({}), // No diff for deletion
          serializedData, // Already serialized before deletion
          'deleted',
          createdAt: DateTime.now(),
        );
        add<SyncDBCache>(dbCache, update: true);
      } catch (e) {
        // Log DBCache creation failures for debugging
        try {
          // ignore: avoid_print
          print(
            'DBCache creation failed for deletion $collectionName|$entityId: $e',
          );
        } catch (_) {}
      }
    }
  });
}