> ## Documentation Index
> Fetch the complete documentation index at: https://www.cometchat.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Stay in Sync

> Catch up on everything that changed while offline, observe sync progress, trigger a manual sync, and manage the local cache with the CometChat Android SDK.

> [accordion] AI Integration Quick Reference
>
> ```kotlin theme={null}
> // Observe the reconnect catch-up sync (conversation phase, then message phase)
> CometChat.addSyncListener("SYNC_LISTENER", object : CometChat.SyncListener() {
>     override fun onConversationSyncCompleted(fetched: List<Conversation>) { /* blind-replace list */ }
>     override fun onMessageSyncCompleted(newPlusUpdates: List<BaseMessage>, outcome: SyncOutcome) { }
>     override fun onMessageSyncError(error: CometChatException?) { }
> })
> CometChat.removeSyncListener("SYNC_LISTENER")
>
> // Poll sync state
> val state: SyncState = CometChat.getSyncState()          // IDLE | SYNCING
> val lastSync: Long = CometChat.getLastSyncTimestamp()    // server epoch seconds, 0 if never
>
> // Trigger a manual catch-up (with an acceptance callback)
> CometChat.forceSyncNow(object : CometChat.CallbackListener<String>() {
>     override fun onSuccess(p: String?) { }
>     override fun onError(e: CometChatException) { /* IN_PROGRESS / COOLDOWN / DISABLED / NOT_LOGGED_IN */ }
> })
>
> // Observe cache rebuilds
> CometChat.addOfflineCacheResetListener("RESET_LISTENER", object : OfflineCacheResetListener() {
>     override fun onOfflineCacheReset(reason: OfflineCacheResetReason, pendingMessagesLost: Int) { }
> })
>
> // Inspect / clear the cache
> val bytes: Long = CometChat.getCacheSize()
> CometChat.clearOfflineCache()                            // destructive; drops the un-sent outbox
> ```

When the device comes back online, the SDK runs a **catch-up sync**: it refreshes the conversation list, then replays everything that changed in your messages since the last sync, and merges the results into the local cache. This page covers how to observe that sync, trigger one on demand, and manage the cache it maintains.

> [!NOTE]
>
> Everything on this page is a no-op unless offline support is active for the logged-in user (`CometChat.isOfflineEnabled()` is `true`). See [Enable Offline Support](https://www.cometchat.com/docs/sdk/android/v5/offline-enable.md).

## How catch-up works

A sync runs automatically whenever the connection settles, including the first connect after login or launch. It never runs on a brief connect-then-drop flap, and overlapping triggers coalesce: at most one follow-up sweep is queued behind the running one. It proceeds in two phases, in order:

1. **Conversation phase** — the conversation list is fetched as one fresh page. A conversation-list UI can blind-replace its list with the result.
2. **Message phase** — the SDK replays the message changelog from the last sync point. New messages and updates to already-cached messages are merged into the cache.

The sync is incremental and safe to repeat: it only moves forward from the last successful point, and a failed or interrupted phase simply resumes on the next reconnect. The conversation refresh does remove conversations you are no longer part of, along with their cached messages, media, and any still-queued messages for them (which fail with reason `DISCARDED`). A first-ever sync (cold start) seeds its starting point from the newest conversation and fetches no message history — older history is reached by scrolling online.

## Listen for sync progress

Register a `CometChat.SyncListener` to observe the lifecycle of every automatic and manual sync. Each phase fires `started`, then exactly one of `completed` / `error`, all on the main thread.

> [tab] Java
>
> ```java theme={null}
> CometChat.addSyncListener("SYNC_LISTENER", new CometChat.SyncListener() {
>     @Override
>     public void onConversationSyncStarted() { }
>
>     @Override
>     public void onConversationSyncCompleted(List<Conversation> fetched) {
>         // The full, fresh conversation page. Blind-replace your list.
>     }
>
>     @Override
>     public void onConversationSyncError(CometChatException error) { }
>
>     @Override
>     public void onMessageSyncStarted() { }
>
>     @Override
>     public void onMessageSyncCompleted(List<BaseMessage> newPlusUpdates, SyncOutcome outcome) {
>         // New + changed messages reconciled this sync. Merge by message id.
>     }
>
>     @Override
>     public void onMessageSyncError(CometChatException error) { }
> });
> ```

> [tab] Kotlin
>
> ```kotlin theme={null}
> CometChat.addSyncListener("SYNC_LISTENER", object : CometChat.SyncListener() {
>     override fun onConversationSyncStarted() {}
>
>     override fun onConversationSyncCompleted(fetched: List<Conversation>) {
>         // The full, fresh conversation page. Blind-replace your list.
>     }
>
>     override fun onConversationSyncError(error: CometChatException?) {}
>
>     override fun onMessageSyncStarted() {}
>
>     override fun onMessageSyncCompleted(newPlusUpdates: List<BaseMessage>, outcome: SyncOutcome) {
>         // New + changed messages reconciled this sync. Merge by message id.
>     }
>
>     override fun onMessageSyncError(error: CometChatException?) {}
> })
> ```

| Callback | When it fires |
| - | - |
| `onConversationSyncStarted()` | The conversation refresh began. |
| `onConversationSyncCompleted(List<Conversation> fetched)` | The refresh succeeded; `fetched` is the full conversation page. |
| `onConversationSyncError(CometChatException)` | The refresh failed. A transport failure leaves the cache untouched; a malformed response still merges the rows it could parse but removes nothing. Either way the refresh retries on the next reconnect. |
| `onMessageSyncStarted()` | The message changelog sweep began. Never fires on a cold start. |
| `onMessageSyncCompleted(List<BaseMessage> newPlusUpdates, SyncOutcome)` | The sweep finished; `newPlusUpdates` carries the new and changed messages. |
| `onMessageSyncError(CometChatException)` | The sweep failed; it resumes on the next reconnect. |

The two phases are independent — a conversation-phase error does not stop the message phase. A phase error is informational: the cache is never left in a wrong state and the sweep resumes automatically.

The `SyncListener` is self-sufficient: `onMessageSyncCompleted` carries the swept messages, including `action` and `call` messages that the `MessageListener` does not deliver, so you can use it without a `MessageListener`.

`onMessageSyncCompleted` reports the outcome:

| `SyncOutcome` | Meaning |
| - | - |
| `CAUGHT_UP` | The changelog was fully replayed; the cache reflects every server change up to the sync point. |
| `PARTIAL` | A page was ingested and the sync point advanced, but a backlog remains. Each sync, automatic or from `forceSyncNow`, drains one page of up to 1000 changes. |

Remove the listener with `CometChat.removeSyncListener("SYNC_LISTENER")`.

## Receiving synced messages

If you already use a `CometChat.MessageListener`, synced messages still arrive there, so you usually do not need a `SyncListener` to keep your chat up to date:

* **Genuinely new** messages arrive one-by-one on the typed callbacks (`onTextMessageReceived`, `onMediaMessageReceived`, `onCustomMessageReceived`, …), each tagged with source `SYNC`.
* **Updates** to already-cached messages arrive together on `onMessagesSynced(List<BaseMessage>)`.

> [tab] Java
>
> ```java theme={null}
> CometChat.addMessageListener("MSG_LISTENER", new CometChat.MessageListener() {
>     @Override
>     public void onTextMessageReceived(TextMessage message) {
>         if (MessageSource.SYNC == message.getSource()) {
>             // Delivered by a catch-up sync. Suppress notification spam if you wish.
>         }
>     }
>
>     // Do the same in onMediaMessageReceived, onCustomMessageReceived and the other typed callbacks.
>
>     @Override
>     public void onMessagesSynced(List<BaseMessage> messages) {
>         // Updates to already-cached messages. Merge by id.
>     }
> });
> ```

> [tab] Kotlin
>
> ```kotlin theme={null}
> CometChat.addMessageListener("MSG_LISTENER", object : CometChat.MessageListener() {
>     override fun onTextMessageReceived(message: TextMessage) {
>         if (MessageSource.SYNC == message.source) {
>             // Delivered by a catch-up sync. Suppress notification spam if you wish.
>         }
>     }
>
>     // Do the same in onMediaMessageReceived, onCustomMessageReceived and the other typed callbacks.
>
>     override fun onMessagesSynced(messages: List<BaseMessage>) {
>         // Updates to already-cached messages. Merge by id.
>     }
> })
> ```

> [!NOTE]
>
> On reconnect, queued messages are sent first, then the sync runs. `forceSyncNow` runs only the sync; it does not send queued messages (use `retryMessage` for those). A message deleted on the server reaches you as an update on `onMessagesSynced`, not as a removal.

## Check sync state

Poll the current sync state and the time of the last completed sync at any time. Both are safe to call on the main thread.

> [tab] Java
>
> ```java theme={null}
> SyncState state = CometChat.getSyncState();          // IDLE or SYNCING
> long lastSync = CometChat.getLastSyncTimestamp();    // server epoch seconds; 0 if never synced
> ```

> [tab] Kotlin
>
> ```kotlin theme={null}
> val state: SyncState = CometChat.getSyncState()      // IDLE or SYNCING
> val lastSync: Long = CometChat.getLastSyncTimestamp() // server epoch seconds; 0 if never synced
> ```

`getSyncState()` returns `SyncState.SYNCING` while a sweep is in flight, otherwise `SyncState.IDLE` (also when offline support is disabled). `getLastSyncTimestamp()` returns a **server-provided** epoch value in seconds, never the device clock, and `0` if the cache has never synced.

## Trigger a manual sync

Call `forceSyncNow` to run a catch-up immediately — for example behind a pull-to-refresh. It is fire-and-forget and routes through the same throttle as the automatic sync, so it will not start a second overlapping sweep or hammer the backend.

Use the callback overload to learn whether the request was accepted; the sync's actual progress and outcome still arrive on your registered `SyncListener`.

> [tab] Java
>
> ```java theme={null}
> CometChat.forceSyncNow(new CometChat.CallbackListener<String>() {
>     @Override
>     public void onSuccess(String result) {
>         // Accepted and started.
>     }
>
>     @Override
>     public void onError(CometChatException e) {
>         // Rejected — see the code.
>     }
> });
> ```

> [tab] Kotlin
>
> ```kotlin theme={null}
> CometChat.forceSyncNow(object : CometChat.CallbackListener<String>() {
>     override fun onSuccess(result: String?) {
>         // Accepted and started.
>     }
>
>     override fun onError(e: CometChatException) {
>         // Rejected — see the code.
>     }
> })
> ```

If you do not need the acceptance result, call the no-argument `CometChat.forceSyncNow()`; a rejected request is silently dropped.

| Rejection code (`CometChatConstants.Errors`) | Meaning |
| - | - |
| `ERROR_OFFLINE_SYNC_IN_PROGRESS` | A sync (automatic or manual) is already running. |
| `ERROR_OFFLINE_SYNC_COOLDOWN` | A sync ran too recently; the error message carries the remaining cooldown in milliseconds (retry-after). |
| `ERROR_OFFLINE_DISABLED` | A user is logged in but offline support is not active. |
| `ERROR_USER_NOT_LOGGED_IN` | Nobody is logged in. |

## When the cache resets

In rare cases the SDK cannot keep the existing cache — for example the encryption key became unrecoverable, or the database file is corrupt. When this happens it rebuilds the cache from scratch and notifies a `OfflineCacheResetListener`. Any un-sent messages that were queued are lost in the rebuild; `pendingMessagesLost` reports how many (it may be unknown).

> [tab] Java
>
> ```java theme={null}
> CometChat.addOfflineCacheResetListener("RESET_LISTENER", new OfflineCacheResetListener() {
>     @Override
>     public void onOfflineCacheReset(OfflineCacheResetReason reason, int pendingMessagesLost) {
>         // The cache was rebuilt. Re-fetch anything you need; it will re-sync from the server.
>     }
> });
> ```

> [tab] Kotlin
>
> ```kotlin theme={null}
> CometChat.addOfflineCacheResetListener("RESET_LISTENER", object : OfflineCacheResetListener() {
>     override fun onOfflineCacheReset(reason: OfflineCacheResetReason, pendingMessagesLost: Int) {
>         // The cache was rebuilt. Re-fetch anything you need; it will re-sync from the server.
>     }
> })
> ```

| `OfflineCacheResetReason` | Cause |
| - | - |
| `KEY_LOST` | The device key could not be recovered (OS update, cleared app data, restored backup); a fresh key was minted. |
| `WRONG_KEY` | The database exists but does not decrypt under the current key. |
| `CORRUPTED` | The database file is corrupt on disk. |
| `ESCALATED` | An unclassified failure recurred across launches and was escalated to a permanent rebuild. |
| `ENCRYPTION_CHANGED` | The `encryption` setting changed, so the on-disk cache was rebuilt in the configured format. |
| `SCHEMA_RESET` | The on-disk cache was written in a format this SDK version cannot read (for example, after rolling back to an older SDK), so it was rebuilt. Queued messages that could still be read are failed with `DISCARDED` first. |

Remove the listener with `CometChat.removeOfflineCacheResetListener("RESET_LISTENER")`. See [Encrypt the Cache](https://www.cometchat.com/docs/sdk/android/v5/offline-encryption.md) for the encryption-related reasons.

## Manage the cache

Read the current cache size, or clear the cache entirely.

> [tab] Java
>
> ```java theme={null}
> long bytes = CometChat.getCacheSize();   // DB + media byte store, in bytes
>
> CometChat.clearOfflineCache();           // wipe the entire per-user cache
> ```

> [tab] Kotlin
>
> ```kotlin theme={null}
> val bytes: Long = CometChat.getCacheSize()  // DB + media byte store, in bytes
>
> CometChat.clearOfflineCache()               // wipe the entire per-user cache
> ```

`getCacheSize()` returns the total cache size in bytes (local database plus the media byte store) as a single figure, or `0` when offline support is disabled or nobody is logged in.

> [!WARNING]
>
> `clearOfflineCache()` is destructive and irreversible. It empties the entire per-user cache — cached messages, conversations, media bytes **and the un-sent outbox**. Each still-queued `PENDING` / `SENDING` message fails with reason `DISCARDED`; messages that had already failed are removed without a further callback. It is a no-op unless offline support is active.

> [!NOTE]
>
> You never need to clear the cache on logout — the SDK does it for you. The cache is stored **per user**: it survives app restarts and a token refresh for the same logged-in user, and is wiped automatically on logout, when the server rejects the auth token, or when a different user or app ID is used. See [Offline Support](https://www.cometchat.com/docs/sdk/android/v5/offline-overview.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.