3

I am using the following observable to call retrofit api then save the response into cache file:

@Override public Observable<StoryCollectionEntity> storyEntityList(final int page) {

       return this.restApi.storyCollection(id, page)
       .doOnNext(saveStoryCollectionToCacheAction)         
   .onErrorResumeNext(CloudNewsDataStore.this.mNewsCache.getStories(page));
            }

This works as expected. my question is: how can i make this observer returns api response periodically?

let's say, user wants to refresh the data every 5 minutes

Fshamri
  • 1,346
  • 4
  • 17
  • 32
  • 1
    Well you might not want this as refreshing the data every 5 minutes = battery drain and therefore loss of users. You want to sync intelligently, use a SyncAdapter. Android OS has heavy optimizations for syncing data using a SyncAdapter and it isn't too hard to setup – Lucas Crawford Dec 14 '15 at 21:03

1 Answers1

2

The interval() operator will emit an item at a given time interval.

You can use this to trigger periodic events like so:

Observable.interval(5, TimeUnit.MINUTES)
            .flatMap(count -> this.restApi.storeCollection(id, page))
            // etc.
Bryan Herbst
  • 66,602
  • 10
  • 133
  • 120
  • what about return statement? should it be return Observable.interval(5, TimeUnit.MINUTES) ... – Fshamri Dec 14 '15 at 21:10
  • If you want to return this Observable, then yes. My example wasn't necessarily meant to be dropped directly into your code, but to be an example that anyone could use in their code. – Bryan Herbst Dec 14 '15 at 21:11
  • is there any detailed example .. plz – Fshamri Dec 14 '15 at 21:20
  • How much more detail do you need? For your particular use case, you literally just put the `interval()` call and a `flatMap()` before the code you already have. – Bryan Herbst Dec 14 '15 at 21:31
  • i have followed your suggestion but ui gets blocked for a while – Fshamri Dec 14 '15 at 21:39
  • It sounds like you aren't correctly using `subscribeOn()` to tell your Observables to do their work on a non-UI thread. – Bryan Herbst Dec 14 '15 at 21:41
  • 1
    You need to use Observable.interval(0, 5, TimeUnit.MINUTES), with the first 0 being the initial delay, before the Observable emits first item. – Martin Dec 11 '17 at 13:32