RxScala: How to keep the thread doing Observable.interval alive?

假如想象 提交于 2019-12-11 10:56:01

问题


I am trying to write a simple RxScala program:

import rx.lang.scala.Observable

import scala.concurrent.duration.DurationInt
import scala.language.{implicitConversions, postfixOps}

object Main {
  def main(args: Array[String]): Unit = {
    val o = Observable.interval(1 second)
    o.subscribe(println(_))
  }
}

When I run this program, I do not see anything printed out. I suspect that this is because that thread producing the numbers in Observable.interval dies. I noticed a call to waitFor(o) in the RxScalaDemo, but I can't figure out where that is imported from.

How do I keep this program running for ever printing the number sequence?


回答1:


You're not seeing anything because your main method exits immediately after you subscribe to the Observable. At that point, your program is done.

A common trick for test programs like this is to read a byte from stdin once you've subscribed.




回答2:


Here is one way to block the main thread from exiting:

val o = Observable.interval(1 second)
val latch = new CountDownLatch(1)
o.subscribe(i => {
  print(i)
  if (i >= 5) latch.countDown()

})
latch.await()

This is a fairly common pattern, use CountDownLatch.await to block the main thread and then countDown the latch when you are done with what you are doing, thus releasing the main thread



来源:https://stackoverflow.com/questions/29439861/rxscala-how-to-keep-the-thread-doing-observable-interval-alive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!