- A
Room
table where the data can be synced to and from likeBloodSugarMeasurement
Sync APIs are the ones where we pull from the server and push new records to the server. Although some API might just pull from the server as well. Here we will only talk about the former. Once the API contracts are finalized, we need to start with following to introduce the API in the code. We will use blood sugar APIs as an example here.
- Start by creating a
@JsonClass
data class
calledBloodSugarMeasurementPayload
and add the API response payload as per the contract. - Add response class
BloodSugarPullResponse
as follows:
@JsonClass(generateAdapter = true)
data class BloodSugarPullResponse(
@Json(name = "blood_sugars")
override val payloads: List<BloodSugarMeasurementPayload>,
@Json(name = "process_token")
override val processToken: String
) : DataPullResponse<BloodSugarMeasurementPayload>
- Save the
processToken
in a shared preference and provide it through the Dagger DI graph. - Create a Retrofit Api interface for adding the HTTP
GET
andPOST
requests for pulling and pushing records respectively. - Add a new
Repository
that implementsSynceableRepository<T,P>
. Use the tableBloodSugarMeasurement
asT
and payload classBloodSugarMeasurementPayload
asP
. This repository is used as an interface between the API and the database. - Implement the overridden methods in the repository class by adding queries in the corresponding
Dao
. While most of the methods here are backed by straightforward queries, there is one in particular that can be challenging.
override fun mergeWithLocalData(payloads: List<BloodSugarMeasurementPayload>): Completable {
return payloads
.toObservable()
.filter { payload ->
val localCopy = dao.getOne(payload.uuid)
localCopy?.syncStatus.canBeOverriddenByServerCopy()
}
.map { it.toDatabaseModel(DONE) }
.toList()
.flatMapCompletable { Completable.fromAction { dao.save(it) } }
}
- Introduce a new class that implements
ModelSync
which will be responsible for syncing. Follow any existing class likeBloodPressureSync
to implement the overridden methods.