Scala Future应用程序在完成之前终止 [英] Scala future app terminates before complete

查看:158
本文介绍了Scala Future应用程序在完成之前终止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅尝试使我的第一个期货投入使用并运行,并进行类似于Akka in Action MEAP书中概述的示例的测试。我想调用Web服务并在将来返回结果。我正在使用scalaxb访问Web服务。我已经在下面概述了代码,但是当我运行它时,应用程序将终止,而无需等待服务的响应。也许有人可以告诉我我缺少什么?

Just trying to get my first futures use up and running and doing a test similar to an example outlined in the Akka in Action MEAP book. I want to call a web service and return the result in a future. I am using scalaxb to access the web service. I have outlined the code below but when I run it the app terminates without waiting for the response from the service. Maybe someone can tell me what I am missing?

import scala.util._
import control.NonFatal
import scala.concurrent._
import ExecutionContext.Implicits.global

object Test {


    val service = (new MyServiceBindings with scalaxb.Soap11Clients with scalaxb.DispatchHttpClients {}).service

    def test = {

        val f = future {

            service.someCall() match {
                case Right(resp) => resp
                case Left(fault) => throw new Exception("Fault: " + fault)}
            }
        }

        f.onComplete {
            case Success(resp) => println("Resp: " + resp)
            case Failure(NonFatal(e)) => println("Fail: " + e)
        }
    }

    def main(args: Array[String]): Unit = {
        test
    }
}


推荐答案

由于主测试内部执行的线程已完成。 Dispatch库内部使用的线程不会阻止程序退出。

It terminates because the main thread that is executed inside your Test has completed. The threads that are used internally by the Dispatch library don't keep the program from exiting.

您需要等待将来,因为这是您唯一的测试应用程式正在执行。将其放在onComplete语句之后。

You would need to wait on the future since this is the only thing your test app is doing. Put this after the onComplete statement.

import scala.concurrent.duration._
Await.ready(f,10.seconds)

现在请记住,这通常是不好的做法。您在这里需要它是因为您的测试应用程序什么都不做,但是在真正的应用程序中,您不想在每次期货调用后都阻塞,因为那样会否定使用期货的意义。

Now bear in mind that this is bad practice usually. You need it here because your test app is doing nothing else, but in a real app, you wouldn't want to block after each futures call, as that would negate the point of using futures.

这篇关于Scala Future应用程序在完成之前终止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆