0

Here is an example using Timer from scala.rx:

package tutorial.webapp

import akka.actor.ActorSystem
import rx.core.{Rx, Var}
import rx._
import rx.ops._

import scala.concurrent.Promise
import scala.concurrent.duration._
import scala.scalajs.js.JSApp
import scala.scalajs.js.annotation.JSExport
import scala.concurrent.ExecutionContext.Implicits.global

/**
 * Created by IDEA on 29/10/15.
 */
object RxAddtionalOps extends JSApp {
  @JSExport
  override def main(): Unit = {
    timer1
  }

  def timer1: Unit = {
    implicit val scheduler = new DomScheduler        
    val t = Timer(100 millis)
    var count = 0
    val o = Obs(t){
      count = count + 1
      println(count)
    }
  }
}

When you run runMain tutorial.webapp.RxAddtionalOps from sbt, the console will be indefinitely blocked. Can I set a limit to the timer? For example, to make it stop emitting events in 2 minutes.

Epicurist
  • 903
  • 11
  • 17
qed
  • 22,298
  • 21
  • 125
  • 196

1 Answers1

1

First of all, Scala is a language for express common programming patterns in a concise, elegant, and type-safe way. So keep your work tidy! Therefore

import akka.actor.ActorSystem
import rx.core.{Rx, Var}
import rx._    
import scala.concurrent.Promise

is a lot of unnecessary noise. And if the target is a JavaScript platform, the Actor system is not available yet, maybe over couple of years.

Why should you fire runMain tutorial.webapp.RxAddtionalOps in sbt, while a simple run command will do?

I used the Timer.kill() method to terminate the execution after a limited time:

package tutorial.webapp

import rx.Obs
import rx.ops.{DomScheduler, Timer}

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
import scala.language.postfixOps
import scala.scalajs.js.JSApp

object RxAddtionalOps extends JSApp {
  val executionStart = scala.compat.Platform.currentTime

  def main(): Unit = {
    timer1()
  }

  def timer1() = {
    implicit val scheduler = new DomScheduler
    val t = Timer(100 millis)

    var count = 0
    Obs(t) {
      count += 1
      println(count)
      if (count >= 19) {
        t.kill()
        println(s"Successfully completed without errors. [within ${
          scala.compat.Platform.currentTime - executionStart
        } ms]")
      }
    }
  }
}

Since it is actually a headless phantom or rhino environment (depending on your build.sbt config) there can be no user initiated interrupt processed.

For completeness here the build.sbt file:

name := "RxAddtionalOps"
version := "1.0"
scalaVersion := "2.11.7"
enablePlugins(ScalaJSPlugin)
scalacOptions ++= Seq("-unchecked", "-deprecation","-feature")
libraryDependencies ++= Seq(
  "com.lihaoyi" %%% "scalarx" % "0.2.8",
  "org.scala-js" %% "scalajs-library" % "0.6.5"
)
Epicurist
  • 903
  • 11
  • 17