Search code examples
javacachingrx-java

how do I make a db call when cache is empty and set value to cache from db?


I have a cache and a database.I am fetching value from cache. if data from cache is empty (due to expiration). I am making a call to database and after fetching data from cache. I will set the value from database to cache.

Single<String> get() {
    return getFromCache().onErrorResumeNext(getFromDatabase());
}

Single<String> getFromCache()  { // or should I use may be here
   //return Single.just("cache");
    return Single.error(new Exception("exception"));
}

Single<String> getFromDatabase() {
    return Single.just("database");
}

Single<String> setDatabase(Single<String> val) {
    return val.map(
            v -> {
                String res = v;
                System.out.println(res);
                return res;
            }
    );
}

Here I am able to call database if value from cache is empty but then I am not able to call method setDatabase.

------------ I have found this way to solve it--------------------------- Since I am new to rxjava. I wanted to what is best way to solve this

Single<String> get() {
    Observable<String> cacheObservable = getFromCache().toObservable();
    Observable<String> databaseObservable = getFromDatabase().toObservable();

    Single<String> result = Observable.concat(cacheObservable, databaseObservable).firstOrError();

    databaseObservable.doOnNext(val-> {
        setDatabase(val);
    });
    return result;
}

Maybe<String> getFromCache()  { // or should I use may be here
   //return Maybe.just("cache");
   return Maybe.empty();
}

Single<String> getFromDatabase() {
    return Single.just("database");
}

void setDatabase(String res) {
    System.out.println(res);
}

Solution

  • You were almost done, use switchIfEmpty for your use case :

    Single<String> get() {
            return getFromCache()
                    .switchIfEmpty(getFromDatabase().doOnSuccess(this::setDatabase));
        }