1

I was looking at the RxScala observables which are created at a given time interval:

val periodic: Observable[Long] = Observable.interval(100 millis)

periodic.foreach(x => println(x))

If I put this in a worksheet, I get this result:

periodic: rx.lang.scala.Observable[Long] = rx.lang.scala.JavaConversions$$anon$2@2cce3493

res0: Unit = ()

This leaves me confused: What do the elements of periodic actually contain?

Do they contain some index? Do they contain the time interval at which they were created?

bsky
  • 19,326
  • 49
  • 155
  • 270

2 Answers2

2

As you can read here http://reactivex.io/documentation/operators/interval.html produced elements are Long values incrementing from 0.

As for your code and results:

Here, you create the observable, and get Observable[Long] assigned to periodic. Everything as expected.

scala> val periodic: Observable[Long] = Observable.interval(100 millis)
periodic: rx.lang.scala.Observable[Long] = rx.lang.scala.JavaConversions$$anon$2@2cce3493

Here, you register a callback, i.e. what happens when value is emmited. The return type of foreach method is Unit as it doesn't have a reasonable value and happens just for the side effect of registering callbacks.

periodic.foreach(x => println(x))
res0: Unit = ()

You don't see actual values because execution stops. Try to insert Thread.sleep.

val periodic: Observable[Long] = Observable.interval(100.millis)
periodic.foreach(x => println(x))
Thread.sleep(1000)

Gives output similar to

periodic: rx.lang.scala.Observable[Long] = rx.lang.scala.JavaConversions$$anon$2@207cb62f

res0: Unit = ()

0
1
2
3
4
5
6
7
8
9
res1: Unit = ()
Łukasz
  • 8,555
  • 2
  • 28
  • 51
1

The problem is that interval is asynchronous, so you´re not waiting for the result.

Another way to wait for the result is use TestSubscriber

def interval(): Unit = {
addHeader("Interval observable")
Observable.interval(createDuration(100))
  .map(n => "New item emitted:" + n)
  .doOnNext(s => print("\n" + s))
  .subscribe();
new TestSubscriber[Subscription].awaitTerminalEvent(1000, TimeUnit.MILLISECONDS);
 }

You can see more examples here https://github.com/politrons/reactiveScala

paul
  • 12,873
  • 23
  • 91
  • 153