2012-11-25 2 views
1

스칼라 2.10에서 새로운 Future API를 정말 좋아하고 간단한 스크립트로 사용하려고합니다. 일부 URL에스칼라 2.10 SBT에서 readLine을 사용하는 선물

  1. HTTP 요청이
  2. 사용자 입력이
  3. 또한 응답 처리 아이디어는 체인으로 모든 것을 구현하는 것입니다

에 따라 필요한 다음과 같이 프로그램의 요점은 Futures (flatmap 등)의 문제가 있지만 여기에 내 문제가있다.

현재 SBT에서 테스트 중이므로 주 스레드가 끝나면 SBT는 REPL로 돌아 간다. 한편, 내 Future 계산은 여전히 ​​내 사용자 입력을 기다리고 있습니다. 입력을 시작하면 2 단계에서 readLine 호출이 SBT의 입력에 관계없이 처리되고있는 것으로 보입니다.

예를 들어 의도 한 입력이 abcdefghijklmnop 인 경우 내 프로그램은 adghip처럼 임의의 하위 집합을 수신하고 완료되면 SBT는 bcefjklmno이 명령이 아님을 알립니다.

어떻게 ...

  1. 지연
  2. 또는는 SBT
  3. 와 함께 싸울 수 없습니다 다른 호출 readLine를 교체 선물 '데몬 스레드 전에 마무리에서 메인 스레드 중 하나 I 수
+1

아, http://stackoverflow.com/questions/10565475/possible-bug-in-scala-2-10-future?rq=1 내 질문에 대한 답변을 얻을 수 있습니다. 수색을 잘 못한다고 생각할 때까지 이걸두고 갈거야. – Dylan

답변

0

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