Skip to content

Instantly share code, notes, and snippets.

@LionZXY
Forked from 1ou/123
Last active September 1, 2017 07:49
Show Gist options
  • Save LionZXY/18c74d78ead9c40cc9d3c30339544b3d to your computer and use it in GitHub Desktop.
Save LionZXY/18c74d78ead9c40cc9d3c30339544b3d to your computer and use it in GitHub Desktop.
Help
package com.skubyev.guesstherace.repositories.images
import com.skubyev.guesstherace.model.ModelWrapper
import com.skubyev.guesstherace.model.data.Cache
import com.skubyev.guesstherace.model.data.Image
import com.skubyev.guesstherace.model.mapper.ImagesMapper
import com.skubyev.guesstherace.model.network.api.images.ImagesApi
import com.skubyev.guesstherace.model.storage.PersistentDatabase
import com.skubyev.guesstherace.utils.ext.subscribeIgnoreResult
import com.skubyev.guesstherace.utils.ext.transitSuccessToEmitter
import io.reactivex.Observable
import io.reactivex.Single
import io.reactivex.schedulers.Schedulers
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class ImagesRepository @Inject constructor(
private var cache: PersistentDatabase<Cache>,
private var mapper: ImagesMapper,
private var database: PersistentDatabase<Image>,
private var api: ImagesApi
) {
private val expirationTime: Long = 1000 * 60 * 60
private val emitter: Subject<ModelWrapper<Image>> = PublishSubject.create()
fun emitter(): Observable<ModelWrapper<Image>> = emitter
fun getData(watchedImages: List<Int>): Single<Image> = cache.findByString(database.type.toString())
.flatMap { cache ->
if (Date().time - cache.time < expirationTime) {
return@flatMap getDataFromDB(watchedImages)
.onErrorResumeNext {
updateCache(null)
return@onErrorResumeNext getDataFromApi()
}
} else {
updateCache(cache)
return@flatMap getDataFromApi()
}
}
private fun getDataFromDB(watchedImages: List<Int>): Single<Image> = database.getRandResult(watchedImages)
.transitSuccessToEmitter(emitter)
private fun getDataFromApi(): Single<Image> = api.getImages()
.map { list ->
list.map { mapper.invoke(it) }
}
.flatMap {
database.removeAllResults()
.doOnComplete {
database.addListResult(it)
.subscribeIgnoreResult()
}
.subscribeIgnoreResult()
return@flatMap Single.just(it[Random().nextInt(it.size)])
.transitSuccessToEmitter(emitter)
}
.subscribeOn(Schedulers.io())
private fun updateCache(cacheItem: Cache?) {
if (cacheItem != null) {
cache.deleteCacheByName(cacheItem.name)
.doOnComplete {
cache.addResult(Cache(database.type.toString()))
.subscribeIgnoreResult()
}
.subscribeIgnoreResult()
} else {
cache.addResult(Cache(database.type.toString()))
.subscribeIgnoreResult()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment