简体   繁体   English

RxJava - 每秒发出一个可观察量

[英]RxJava - emit an observable every second

I am making a timer in Android using RxJava. 我正在使用RxJava在Android中制作计时器。 I need to make a timer in RxJava to emit an observable every second. 我需要在RxJava中创建一个计时器,每秒发出一个可观察量。 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. 在使用Observable ,它是完全正确的。

For example, I put your snippet inside onCreate(...) of my MainActivity : 例如,我将您的代码段放在我的MainActivity onCreate(...)中:

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. 此外,您可能不需要.timeInterval()因为Observable.interval(...)本身会以指定的速率发出连续数字,而.timeInterval()只是将其转换为发出排放之间经过的时间间隔。

In your subscribe() you don't consume the longTimeInterval object that's returned by the timeInterval() operator. subscribe()您不使用timeInterval()运算符返回的longTimeInterval对象。

Correct version: 正确版本:

.subscribe(longTimeInterval -> {
     Log.d(LOG_TAG, "&&&& on timer"); 
}

Also I think you don't need the timeInterval() operator at all. 另外我认为你根本不需要timeInterval()运算符。 Observable.interval() will emit an observable every second in your case, which I guess is what you want. Observable.interval()会在你的情况下每秒发出一个observable,我想这就是你想要的。 timeInterval() transforms that to an observable that holds the exact time difference between two events occur, I doubt you'll need that. timeInterval()将它转换为一个可以保存两个事件之间确切时间差的observable,我怀疑你是否需要它。

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. 在Kotlin&RxJava 2.0.2中,只需定义一个带有initialDelay 0和period 1的Observable Interval,它将每秒发出一个列表项。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM