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") })
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With