![]() |
RxJava - emit an observable every second - Printable Version +- 0Day Forums (https://0day.red) +-- Forum: Coding (https://0day.red/Forum-Coding) +--- Forum: Kotlin (https://0day.red/Forum-Kotlin) +--- Thread: RxJava - emit an observable every second (/Thread-RxJava-emit-an-observable-every-second) |
RxJava - emit an observable every second - banjermasin529 - 07-20-2023 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") }) RE: RxJava - emit an observable every second - overstressesczdtveksz - 07-20-2023 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. RE: RxJava - emit an observable every second - Mrjerrywzk - 07-20-2023 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]: RE: RxJava - emit an observable every second - extortionists588050 - 07-20-2023 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) |