sync method

Future<void> sync({
  1. List<String>? cids,
  2. DateTime? lastSyncAt,
})

Get the events missed while offline to sync the offline storage Will automatically fetch cids and lastSyncedAt if persistenceEnabled

Implementation

Future<void> sync({List<String>? cids, DateTime? lastSyncAt}) {
  return _syncLock.synchronized(() async {
    final channels = cids ?? await chatPersistenceClient?.getChannelCids();
    if (channels == null || channels.isEmpty) {
      return;
    }

    final syncAt = lastSyncAt ?? await chatPersistenceClient?.getLastSyncAt();
    if (syncAt == null) {
      return;
    }

    try {
      final res = await _chatApi.general.sync(channels, syncAt);
      final events = res.events
        ..sort((a, b) => a.createdAt.compareTo(b.createdAt));

      for (final event in events) {
        logger.fine('event.type: ${event.type}');
        final messageText = event.message?.text;
        if (messageText != null) {
          logger.fine('event.message.text: $messageText');
        }
        handleEvent(event);
      }

      final now = DateTime.now();
      _lastSyncedAt = now;
      chatPersistenceClient?.updateLastSyncAt(now);
    } catch (e, stk) {
      logger.severe('Error during sync', e, stk);
    }
  });
}