【问题标题】:Set a limit to scala.rx timer设置 scala.rx 计时器的限制
【发布时间】:2016-01-30 17:33:17
【问题描述】:

这是一个使用来自 scala.rx 的 Timer 的示例:

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)
    }
  }
}

当你从 sbt 运行 runMain tutorial.webapp.RxAddtionalOps 时,控制台将被无限期地阻塞。我可以设置计时器的限制吗?例如,让它在 2 分钟内停止发射事件。

【问题讨论】:

    标签: scala asynchronous scala.js scala.rx


    【解决方案1】:

    首先,Scala 是一种以简洁、优雅和类型安全的方式表达常见编程模式的语言。所以保持你的工作整洁! 因此

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

    是很多不必要的噪音。如果目标是 JavaScript 平台,Actor 系统可能还没有,可能要几年时间。

    为什么要在 sbt 中触发 runMain tutorial.webapp.RxAddtionalOps,而一个简单的 run 命令就可以了?

    我使用 Timer.kill() 方法在有限的时间后终止执行:

    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]")
          }
        }
      }
    }
    

    由于它实际上是一个无头幻象或 rhino 环境(取决于您的 build.sbt 配置),因此无法处理用户启动的中断。

    为了完整起见,这里的 build.sbt 文件:

    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"
    )
    

    【讨论】:

      猜你喜欢
      • 2012-04-26
      • 2014-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-19
      • 2011-07-25
      相关资源
      最近更新 更多