Faiz
Faiz

Reputation: 51

save and get the cache data from disk in RxJava

I am using Rx in my app to perform api calls where i am looking forward to do it in the following sequence

  1. check if there is an internet connection
  2. if true (from 1), call api for result
  3. then save the result in the disk cache
  4. if false (from 1) send error notification and load data from disk cache.

for that i have Observable that get the stored data from disk cache:

@Override
public Observable<StoryCollectionEntity> getStroty(String id) {
            return Observable.create(new Observable.OnSubscribe<StoryCollectionEntity>() {
                @Override
                public void call(Subscriber<? super StoryCollectionEntity> subscriber) {
                   //readFileContent
                   //deserializeS fileContent
                   subscriber.onNext(storyCollectionEntity);
                   subscriber.onCompleted();
                   subscriber.onError()
                } 
            });
        }

also the following to save cache in the disk:

    @Override
        public void putStory(StoryCollectionEntity storyCollectionEntity) {
           // save in the disk
        }

I am successfully able to save and retrieve the data but feel my code is not good enough as sometimes the data retrived from api is not being saved in disk cache also i am calling the cached data on onErrorResumeNext which i think is wrong way.

here is my code:

    @Override
     public Observable<StoryCollectionEntity> storyEntityList() {
     return this.restApi.storyCollection()
    .doOnNext(saveStoryCollectionToCache)
    .onErrorResumeNext(
       storyCache.getStroty(StoryCollectionEntity.class.getName()));
   }

here saveStoryCollectionToCache is:

private final Action1<StoryCollectionEntity> saveStoryCollectionToCache =
  storyCollectionEntity ->
    {
      if (storyCollectionEntity != null) {
                   storyCache.putStory(storyCollectionEntity);
                   } };

can you please help on how to achieve best implementation to my case. also how can i check for internet connection before i call restApi?

Thanks a lot

Upvotes: 0

Views: 2759

Answers (1)

wnc_21
wnc_21

Reputation: 1771

You shouldn't mix everithing into a single observable. Please read this post, explaining how to split this things. http://blog.danlew.net/2015/06/22/loading-data-from-multiple-sources-with-rxjava/

Upvotes: 3

Related Questions