Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJava - emit an observable every second

I am making a timer in Android using RxJava. I need to make a timer in RxJava to emit an observable every second. I have tried the following but with no luck. Any thoughts on what I am doing wrong?

Observable.interval(1000L, TimeUnit.MILLISECONDS)
          .timeInterval()
          .observeOn(AndroidSchedulers.mainThread())
          .subscribe({Log.d(LOG_TAG, "&&&& on timer") })
like image 394
fergdev Avatar asked Feb 28 '16 21:02

fergdev


1 Answers

Your code seems not to be called. Check whether it is executed and when. As of working with Observable, it is completely correct.

For example, I put your snippet inside onCreate(...) of my MainActivity:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    Observable.interval(1000L, TimeUnit.MILLISECONDS)
            .timeInterval()
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe { Log.d("tag", "&&&& on timer") }
    // ...
}

And it works:

https://www.dropbox.com/s/jxkm5ol8l5idyji/observable_interval.png?dl=0

Also, probably you don't need .timeInterval() because Observable.interval(...) itself emits sequential numbers within the specified rate, and .timeInterval() just transforms it to emit the time intervals elapsed between the emissions.

like image 133
hotkey Avatar answered Sep 18 '22 18:09

hotkey