Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android RX - Observable.timer only firing once

So I am trying to create an observable which fires on a regular basis, but for some reason which I cannot figure out, it only fires once. Can anyone see what I am doing wrong?

Observable<Long> observable = Observable.timer(delay, TimeUnit.SECONDS, Schedulers.io());          subscription =  observable                 .subscribeOn(Schedulers.io())                 .observeOn(AndroidSchedulers.mainThread())                 .subscribe(new Action1<Long>() {                     @Override                     public void call(Long aLong) {                         searchByStockHelper.requestRemoteSearchByStock();                     }                 }); 

currently delay is set to 2

like image 816
James King Avatar asked Sep 11 '15 12:09

James King


2 Answers

The documentation for the timer operator says this:

Create an Observable that emits a particular item after a given delay

Thus the behavior you are observing is expected- timer() emits just a single item after a delay.

The interval operator, on the other hand, will emit items spaced out with a given interval.

For example, this Observable will emit an item every second:

Observable.interval(1, TimeUnit.SECONDS); 
like image 50
Bryan Herbst Avatar answered Sep 17 '22 20:09

Bryan Herbst


I know topic is old but maybe for future visitors. (5 min count down timer)

Disposable timerDisposable = Observable.interval(1,TimeUnit.SECONDS, Schedulers.io())         .take(300)         .map(v -> 300 - v)         .subscribe(             onNext -> {                 //on every second pass trigger             },             onError -> {                 //do on error             },             () -> {                 //do on complete             },             onSubscribe -> {                 //do once on subscription             }); 
like image 22
Jakub S. Avatar answered Sep 20 '22 20:09

Jakub S.