Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 355 Vote(s) - 3.47 Average
  • 1
  • 2
  • 3
  • 4
  • 5
RxJava - emit an observable every second

#1
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") })
Reply

#2
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.
Reply

#3
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:

[![

[To see links please register here]

][1]][1]

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.

[1]:
Reply

#4
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)
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through