Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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.
–
In your subscribe()
you don't consume the longTimeInterval
object that's returned by the timeInterval()
operator.
Correct version:
.subscribe(longTimeInterval -> {
Log.d(LOG_TAG, "&&&& on timer");
Also I think you don't need the timeInterval()
operator at all. Observable.interval()
will emit an observable every second in your case, which I guess is what you want. timeInterval()
transforms that to an observable that holds the exact time difference between two events occur, I doubt you'll need that.
–
In Kotlin & RxJava 2.0.2 simply define an Observable Interval with an initialDelay
0 and period
1 which will emit list item each second.
val list = IntRange(0, 9).toList()
val disposable = Observable
.interval(0,1, TimeUnit.SECONDS)
.map { i -> list[i.toInt()] }
.take(list.size.toLong())
.subscribe {
println("item: $it")
Thread.sleep(11000)
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.