These are chat archives for ReactiveX/RxJava

16th
Nov 2016
pavel.shackih
@pavelshackih
Nov 16 2016 08:57
Hi! I'm trying to implement very simple cache manager using RxJava2. Is there a way to simplify fromServer fun by removing ReplaySubject? Thanks!
class ConfigManager() {

    @Volatile private var isDirty = true
    @Volatile private var cachedConfig: String? = null
    private var replay: ReplaySubject<String>? = null

    fun getConfig(): Single<String> = Observable.concat(fromCache().toObservable(), fromServer().toObservable()).firstOrError()

    private fun fromCache(): Maybe<String> = Maybe.create { if (isCacheExists()) it.onSuccess(cachedConfig) else it.onComplete() }

    private fun isCacheExists() = !isDirty && cachedConfig != null

    private fun fromServer(): Single<String> {
        if (replay == null) {
            replay = ReplaySubject.create()
            return Single.fromCallable { hardOperation() }
                    .doOnSuccess {
                        replay?.onNext(it)
                        replay?.onComplete()
                        setCache(it)
                    }
                    .doOnError {
                        replay?.onError(it)
                    }
        }
        return replay?.firstOrError()!!
    }

    private fun setCache(cache: String) {
        cachedConfig = cache
        isDirty = false
    }

    fun reload() {
        isDirty = true
        replay = null
    }
}