Search code examples
scalatimerscala.jsscala.rx

Using Timer from scala.rx


Can someone give me a simple example of using the Timer from Li Haoyi's scala.rx that doesn't depend on an Akka or any other libraries besides scalajs, dom, and rx?

The example of a Timer from Haoyi's GitHub is:

import scala.concurrent.duration._
implicit val scheduler = new AkkaScheduler(akka.actor.ActorSystem())

val t = Timer(100 millis)
var count = 0  
val o = Obs(t){
  count = count + 1
}

println(count) // 3
println(count) // 8
println(count) // 13

However, this uses Akka.

Looking in the scala.rx api, the way to create a rx.ops.Timer is:

new Timer(interval: FiniteDuration, delay: FiniteDuration)(implicit scheduler: Scheduler, p: Propagator[P], ec: ExecutionContext)

where Scheduler is a trait defined as:

abstract def scheduleOnce[T](interval: FiniteDuration)(thunk: ⇒ T)(implicit executor: ExecutionContext): Unit

The Scheduler is an Akka ActorSystem on the JVM and the setTimeout function in JavaScript."

Though all the information in the api is useful, I still can't get the right syntax for a simple timer.


Solution

  • If I understand correctly from the documentation, you simply have to provide an implicit DomScheduler in scope instead of an AkkaScheduler:

    import rx.ops._
    
    implicit val scheduler = new DomScheduler