首页 文章

Scala 2.10期货与SBT中的readLine

提问于
浏览
1

我非常喜欢Scala 2.10中的新 Future API,我正在尝试将它用于一个简单的脚本 . 该计划的要点如下:

  • 对某个URL的HTTP请求

  • 根据响应需要用户输入

  • 进一步处理

我们的想法是将所有东西都作为期货链(flatmap等)来实现,但这是我的问题:

我目前正在SBT中进行测试,因此当主线程完成时,SBT将重新进入其REPL . 同时,我的 Future 计算仍在等待我的用户输入 . 一旦我开始尝试输入,似乎步骤2中的 readLine 呼叫正在与SBT正在尝试做的任何输入作斗争 .

例如,如果我的预期输入是 abcdefghijklmnop ,我的程序会收到一个随机的子集,如 adghip ,然后当它完成时,SBT会告诉我 bcefjklmno 不是命令 .

我怎么能......

  • 延迟主线程在Futures的守护程序线程之前完成

  • orreadLine 替换为其他一些不与SBT抗争的电话

1 回答

  • 0

    使用 scala.concurrent.AwaitJavaDoc) . 也许下面的草图是你要找的?

    import scala.concurrent.Future
    import scala.concurrent.ExecutionContext._
    import scala.concurrent.duration.Duration
    import scala.concurrent.duration._
    import scala.concurrent.Await
    import java.util.concurrent.Executors.newScheduledThreadPool
    
    object Test {
      implicit val executor = fromExecutorService(newScheduledThreadPool(10))
      val timeout = 30 seconds
    
      def main(args: Array[String]) {
        val f =
          // Make HTTP request, which yields a string (say); simulated here as follows
          Future[String] {
            Thread.sleep(1000)
            "Response"
          }.
            // Read input
            map {
              response =>
                println("Please state your problem: ")
                val ln = readLine() // Note: this is blocking.
                (response, ln)
            }.
            // Futher processing
            map {
              case (response, input) =>
                println("Response: " + response + ", input: " + input)
            }
        Await.ready(f, timeout)
      }
    }
    

相关问题