1

I really like the new Future API in Scala 2.10, and I'm trying to use it for a simple script. The gist of the program is as follows:

  1. HTTP request to some URL
  2. User input required based on the response
  3. Further processing

The idea is to implement everything as a chain of Futures (flatmap, etc.), but here's my problem:

I'm currently doing my testing in SBT, so when the main thread finishes, SBT goes back into its REPL. Meanwhile, my Future computation is still waiting on my user input. Once I start trying to type, it seems that the readLine call in step 2 is fighting with whatever input SBT is trying to do.

For example, if my intended input was abcdefghijklmnop, my program would receive a random subset of that, like adghip, and then when it finishes, SBT will tell me that bcefjklmno isn't a command.

How can I either...

  1. Delay the main thread from finishing before the Futures' daemon threads
  2. or Replace readLine with some other call that won't fight with SBT
Emil Ivanov
  • 37,300
  • 12
  • 75
  • 90
Dylan
  • 13,645
  • 3
  • 40
  • 67
  • 1
    Ahh, http://stackoverflow.com/questions/10565475/possible-bug-in-scala-2-10-future?rq=1 might answer my question. Gonna leave this up until I feel too bad for being bad at searching. – Dylan Nov 25 '12 at 19:30

1 Answers1

0

Use scala.concurrent.Await (JavaDoc). Maybe the following sketch is what you are looking for?

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)
  }
}
Hbf
  • 3,074
  • 3
  • 23
  • 32