Shwetanka
Shwetanka

Reputation: 5036

scala - dispatch example not working

I'm following the very first example in the dispatchdocs -

    val svc = url("http://api.hostip.info/country.php")
    val country = Http(svc OK as.String)
    for (c <- country)
      println(c)

I do not get any output printed. When I change it to below to make blocking call then I get the output.

val res = country()
println(res)

Need help with this.

Full program-

import dispatch._
object DispatchTest {

  def main(args: Array[String]) {
    val svc = url("http://api.hostip.info/country.php")
    val country = Http(svc OK as.String)
    for (c <- country)
      println(c)
  }
}

Upvotes: 3

Views: 1715

Answers (2)

NIA
NIA

Reputation: 2543

Hmm, not sure here, but maybe the problem is that your main thread is finished so fast, that background thread (in which Dispatch works asynchronously) has no time for taking action?

To check this you may try to insert a delay:

for (c <- country) // Here we spawn a background thread!
  println(c)

Thread.sleep(500) // So let's wait half a second for it to work

Of course, in real program you should never need to do this.

Another option for delay is simply a readLine() in the end of main.

Upvotes: 6

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297295

It works here:

scala> import dispatch._
import dispatch._

scala> val svc = url("http://api.hostip.info/country.php")
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
svc: com.ning.http.client.RequestBuilder = com.ning.http.client.RequestBuilder@2f823290

scala> val country = Http(svc OK as.String)
country: dispatch.Promise[String] = Promise(-incomplete-)

scala> for (c <- country)
     |   println(c)

scala> BR

Note that BR which appeared after the prompt.

Are you sure the country wasn't printed somewhere but you didn't notice because it was mixed up with other output?

Upvotes: 0

Related Questions