2015-08-09 36 views
2
object Executor extends App { 
    implicit val system = ActorSystem() 
    implicit val materializer = ActorMaterializer() 
    implicit val ec = system.dispatcher 
    import akka.stream.io._ 
    val file = new File("res/AdviceAnimals.tsv") 
    import akka.stream.io.Implicits._ 
    val foreach: Future[Long] = SynchronousFileSource(file) 
    .to(Sink.outputStream(()=>System.out)) 
    .run() 

    foreach onComplete { v => 
    println(s"the foreach is ${v.get}") // the will not be print 
    } 
} 

但如果我將Sink.outputStream(()=>System.out)更改爲Sink.ignore,則會打印println(s"the foreach is ${v.get}")未來不完整?

有人可以解釋爲什麼嗎?

+0

從字符串中提取表達式。 'val vGet = v.get; println(s「foreach是$ vGet」) - 然後會發生什麼? –

+0

我試過了,沒有成功,我猜''Sink.outputStream((()=> System.out)'已經被阻塞了。但我不知道爲什麼? – daixfnwpu

+0

你是什麼意思,「不成功」?什麼症狀?你還會得到「未來不完整」的信息嗎? O/W你有一個不同的問題。我強烈懷疑你必須閱讀關於'onComplete'參數的文檔。 –

回答

2

您並未等待流完成,而是您的主方法(Executor的主體)將完成,並且由於主方法已完成,JVM將關閉。

你想要做的就是阻止該線程,並在未來完成之前不退出應用程序。

object Executor extends App { 
    // ...your stuff with streams... 
    val yourFuture: Future[Long] = ??? 

    val result = Await.result(yourFuture, 5 seconds) 
    println(s"the foreach is ${result}") 

    // stop the actor system (or it will keep the app alive) 
    system.terminate() 
} 
+0

好吧,這並不完全正確,因爲在ActorSystem關閉之前應用程序不會退出。 –

0

巧合的是,我創建了幾乎相同的應用程序來測試/玩阿卡流。 導入的implicits是否會導致問題? 該應用軟件爲我工作得很好:

object PrintAllInFile extends App { 
    val file = new java.io.File("data.txt") 

    implicit val system = ActorSystem("test") 
    implicit val mat = ActorMaterializer() 
    implicit val ec  = system.dispatcher 

    SynchronousFileSource(file) 
    .to(Sink.outputStream(() => System.out)) 
    .run() 
    .onComplete(_ => system.shutdown()) 
} 

注意ActorSystem在「的onComplete」停止。否則,該應用程序不會退出。