Skip to content

Instantly share code, notes, and snippets.

@lukaspili
Created Feb 21, 2018
Embed
What would you like to do?
1.kt
interface ProductApi {
@GET("categories")
fun categories(): Observable<Response<List<CategoryData>>>
@GET("produitscat")
fun products(): Observable<Response<List<ProductData>>>
}
class ProductDatabase(private val database: Database) {
fun allMatchingCategory(categoryId: Int): Flowable<List<ProductData>> =
database.query {
where(ProductData::class.java)
.equalTo("id_categorie", categoryId)
.sort("ordre")
}
fun update(data: List<ProductData>) =
database.transaction {
// find all products that are in database but not in JSON anymore
val toDelete = where(ProductData::class.java)
.not()
.`in`("id", data.map { it.id }.toTypedArray())
.findAll()
if (toDelete.isNotEmpty()) {
// delete along cart items referencing the deprecated products
where(CartItemData::class.java)
.`in`("id", toDelete.map { it.id }.toTypedArray())
.findAll()
.deleteAllFromRealm()
// delete along favorites referencing the deprecated products
where(FavoriteData::class.java)
.`in`("id", toDelete.map { it.id }.toTypedArray())
.findAll()
.deleteAllFromRealm()
// finally, delete deprecated products
toDelete.deleteAllFromRealm()
}
insertOrUpdate(data)
}
}
class ProductRepository(private val api: Api,
private val productDatabase: ProductDatabase) {
fun update(): Completable =
api.product.products()
.flatMapCompletable {
if (it.isSuccessful) {
productDatabase.update(it.body()!!)
} else {
Completable.error(ApiError())
}
}
.onErrorResumeNext { Completable.error(ApiError(it)) }
fun allMatchingCategory(categoryId: Int): Flowable<List<ProductData>> =
productDatabase.allMatchingCategory(categoryId)
}
class ProductService(private val productRepository: ProductRepository,
private val cartRepository: CartRepository,
private val favoriteRepository: FavoriteRepository) {
fun allMatchingCategory(categoryId: Int): Flowable<List<ProductWithCartAndFavoriteData>> =
Flowable.combineLatest(
productRepository.allMatchingCategory(categoryId),
cartRepository.allItems(),
favoriteRepository.all(),
Function3 { products, cartItems, favorites ->
products.map { product ->
ProductWithCartAndFavoriteData(
product,
cartItems.find { it.id == product.id }?.quantity
?: 0,
favorites.find { it.id == product.id } != null
)
}
}
)
fun update(): Observable<ActionTask> =
productRepository.update().asTask()
data class ProductWithCartAndFavoriteData(
val product: ProductData,
val cartQuantity: Int,
val isFavorite: Boolean
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment