Purpose of the Updater

The Updater is designed to handle data synchronization from the local Store to a remote data source. It provides:

  • Data Mutation Synchronization: Ensures that any changes made locally are propagated to the remote data source.
  • Completion Handling: Enables custom logic to be executed upon the completion of the network operation.

APIs

Updater

The Updater interface has the following structure:

interface Updater<Key : Any, Output : Any, Response : Any> {
    suspend fun post(key: Key, value: Output): UpdaterResult
    val onCompletion: OnUpdaterCompletion<Response>?
}
Key
Any
required

The type representing the key used to identify the data to fetch. For example, if fetching a list of posts, this could be an Int representing the post ID.

Output
Any
required

The type representing the domain data model representation of the item being retrieved.

Response
Any
required

The type representing the response received after updating the remote data source.

post

Makes a network request to update the remote data source with the provided data.

key
Key
required

The unique key identifying the data item.

value
Output
required

The data to be written, in the domain model format.

onCompletion

An optional callback executed upon the completion of the network operation.

Data Flow

Writing Data and Synchronization

When a data mutation occurs in the lcoal Store, the Updater is invoked to synchronize the change with the remote data source.

1

Local Mutation

A write request is made to the Store, updating the local data.

val writeRequest = StoreWriteRequest.of(key, value)
mutableStore.write(writeRequest)
2

Queue Write Request

The write request is added to a per-key write request queue in the RealMutableStore.

addWriteRequestToQueue(writeRequest)
3

Update Local Store

The RealMutableStore writes the new value to the local data source using a delegate RealStore.

delegate.write(writeRequest.key, writeRequest.value)
4

Attempt Server Synchronization

The Updater attempts to post the latest value to the remote data source.

val updaterResult = updater.post(writeRequest.key, writeRequest.value)
5

Handle Updater Result

A

Success

  • Updates the write request queue, removing processed requests.

  • Clears any failed sync records from the Bookkeeper.

  • Executes onCompletion callback if provided.

B

Failure

  • Records the failed attempt using the Bookkeeper.

  • Leaves the write request in the queue for future retries.

6

Emit Write Response

The RealMutableStore emits a StoreWriteResponse to consumers, indicating the success or failure of the write operation.

emit(storeWriteResponse)

Best Practices

  • Handle Updater Results Appropriately: Use the onCompletion callback to perform actions based on success or failure.
  • Provide a Bookkeeper: The Bookkeeper is responsible for recording failed sync attempts, allowing the RealMutableStore to retry failed operations by invoking the Updater again.