-
-
Notifications
You must be signed in to change notification settings - Fork 0
Repo Setup
Each repository should have two stores, asynchronous store and synchronous.
class AsyncComplexModelStore : AbstractAsyncIDataStore<ComplexModel>()
In this example, no methods are overriden as the asynchronous version of the repo is not consumed
class SyncComplexModelStore(private val preferenceDatabase: PreferenceDatabase<Int, ComplexModel>) : AbstractSyncIDataStore<ComplexModel>() {
val TAG = LogUtil.makeTag(SyncComplexModelStore::class.java)
override fun all(args: Map<String, Any?>?): Pair<List<ComplexModel>?, Any?> {
if (args == null) throw IllegalArgumentException("number and times args must be passed")
val number = args[NUMBER_ARG] as Int
val times = args[TIMES_ARG] as Int
LogUtil.e(TAG, "repo args ", number, times)
val savedModels = preferenceDatabase.all().first
return if (savedModels.isEmpty()) {
val models = List<ComplexModel>()
(0 until number * times).forEach {
models.add(ComplexModel().apply {
uId = it + 1
name = getId().toString() + "n"
isModel = getId().rem(2) == 0
})
}
Pair(models, preferenceDatabase.save(models))
} else Pair(List(savedModels), "from cache")
}
override fun one(args: Map<String, Any?>?): Pair<ComplexModel?, Any?> {
if (args == null || !args.containsKey(ID_ARG)) throw IllegalArgumentException("ID_ARG must be passed in args")
return preferenceDatabase.one(args)
}
}
In this store, all method is overriden to fetch all items from the preferenceDatabase, one method is overriden to fetch one item from preference database
If there's need to pass extra arguments to the store methods, these arguments are passed in the args parameter, In our case, number and times are passed through the args parameter of the all method
val complexStore: StoreRepository<ComplexModel> by lazy {
StoreRepository.of(
SyncComplexModelStore::class,
AsyncComplexModelStore::class,
arrayOf(PreferenceDatabase("models",
object : DoubleConverter<Int, String, String> {
override fun deserialize(e: String): Int = e.toInt()
override fun serialize(t: Int): String = t.toString()
},
object : DoubleConverter<ComplexModel, JSONObject, JSONObject> {
override fun deserialize(e: JSONObject): ComplexModel = ComplexModel().apply {
name = e.getString("name")
isModel = e.getBoolean("isModel")
}
override fun serialize(t: ComplexModel): JSONObject = JSONObject().apply {
put("name", t.name)
put("isModel", t.isModel)
}
})))
}
The static of method models the object, passed to it are the two classes and array of parameters of constructors of the classes, for instance, the SyncComplexModelStore takes PreferenceDatabase dependency, so an instance of Preference database is passed in in arrayOf argument of Repository.of method