I'm getting data from an API using scala's Dispatch library.
In main, I have a function getSensorList() which returns a list of sensors attached to an ID for a device.
Dispatch uses Futures to do a request Dispatch library
How do I return the future back to main?
I followed this post to implement what I have: Accessing value returned by scala futures
import dispatch._, Defaults._
import scala.util.{Success, Failure}
import scala.concurrent.duration._
def getSensorList(uuid:String) = Future[String] {
val svc = url("https://example_api.com/services/api/v1/sensors/" + uuid + "/")
val response : Future[String] = Http(svc OK as.String)
}
object DispatchTestFunction{
def main (args: Array[String]) {
val result = getSensorList("example_device_ID)
result onComplete {
case Success(content) => {
println("Successful response" + content)
}
case Failure(t) => {
println("An error has occurred: " + t.getMessage)
}
}
}
}
Thanks for your help.
The API returns JSON type data therefore should result be of type JSON?
The error that I have with my code is Type mismatch, expected string: actual is unit
I have the return type of the future defined as a string but the complier looks at the last line of the function and thinks it should be of type unit - i.e. that it returns notting?
Thanks
import dispatch._, Defaults._
import scala.util.{Success, Failure}
def getSensorList(uuid:String) = Future[String] {
val svc = url("https://example_api.com/services/api/v1/sensors/" + uuid + "/")
val response : Future[String] = Http(svc OK as.String)
}
object DispatchTestFunction{
def main (args: Array[String]) {
val result = getSensorList("example_device_ID")
result onComplete {
case Success(content) => {
println("Successful response" + content)
}
case Failure(t) => {
println("An error has occurred: " + t.getMessage)
}
}
}
}
result.) How do you want to get theFuturein themain? For me it seems you already have it. Not sure what you want to achieve. Do you want toAwaitthe result? Ormap? - Gábor Bakosresultbe of type JSON? Does that exist in Scala. - scalauserval result: Future[/*List[*/JValue/*]*/] = .... An IDE or REPL can tell. For an akka/ScalaFutureyou can get the result byAwaitto it (docs.scala-lang.org/overviews/core/futures.html#blocking), in case you prefer to keep it in aFuture, justmaptheresultto something else. - Gábor Bakos