【问题标题】:Scala 2.10 Futures with readLine in SBTSBT 中带有 readLine 的 Scala 2.10 期货
【发布时间】:2012-11-25 19:27:41
【问题描述】:

我真的很喜欢 Scala 2.10 中的新 Future API,我正在尝试将它用于一个简单的脚本。该程序的要点如下:

  1. 对某个 URL 的 HTTP 请求
  2. 根据响应需要用户输入
  3. 进一步处理

这个想法是将所有东西都实现为 Futures 链(平面图等),但这是我的问题:

我目前正在 SBT 中进行测试,所以当主线程完成时,SBT 会回到它的 REPL。同时,我的Future 计算仍在等待我的用户输入。一旦我开始尝试输入,似乎第 2 步中的 readLine 调用正在与 SBT 尝试执行的任何输入发生冲突。

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

我怎么能...

  1. 在 Futures 的守护线程之前延迟主线程完成
  2. readLine 替换为不会与 SBT 冲突的其他调用

【问题讨论】:

标签: scala future


【解决方案1】:

使用scala.concurrent.Await (JavaDoc)。也许您正在寻找以下草图?

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-05
    • 2013-07-08
    • 2013-09-01
    • 2013-12-08
    相关资源
    最近更新 更多