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:

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.

Kotlin相关问答推荐

如何在使用Kotlin Coroutines时检测和记录何时出现背压

某些公共函数显然不能在类实例上访问;Klaxon示例

"Kotlin中的表达式

处理合成层次 struct 中的深层按钮以切换视图

如何定义一个函数来接受任何具有特定字段的数据类

如何在 Kotlin 中初始化 Short 数组?

使用调度程序运行异步 Kotlin 代码

如何将光标从一个文本字段传递到 Jetpack Compose 中的其他文本字段?

如何在 Jetpack Compose 中启动和停止动画

如果不在可组合函数中,如何获取 stringResource

Kotlin SAM/功能接口抛出 AbstractMethodError

如何在kotlin中使用协程每秒调用一个函数

具有多个不同类型来源的 LiveData

在构造函数中仅注入某些参数

requireNotNull vs sure !! 操作符

我们如何在Java注释声明中引用Kotlin常量?

Kotlin:相互递归函数的尾部递归

你如何在 Kotlin 中注释 Pair 参数?

如何修复未解析的参考生命周期范围?

项目不会使用 Kotlin 1.1.3 构建