Skip to content

Instantly share code, notes, and snippets.

@raghothams
Last active August 29, 2015 14:18
Show Gist options
  • Save raghothams/ffc51d00490f86e855d0 to your computer and use it in GitHub Desktop.
Save raghothams/ffc51d00490f86e855d0 to your computer and use it in GitHub Desktop.
Trying out Futures in scala with callbacks
/**
* Created by init on 4/4/15.
*/
import scala.concurrent._
import ExecutionContext.Implicits.global
import scala.util.{Failure, Success}
// implicit execution context
import scala.io.Source
object ScalaFuture extends App {
def getAPIResponse() ={
val result = Source.fromURL("https://api.instagram.com/v1/users/search?access_token=1808215450.97d681d.36499ceeca304b2f9ac4383ff712dda3&q=raghothams");
/*
adding bad API token to test failure callback
val result = Source.fromURL("https://api.instagram.com/v1/users/search?access_token=1808215450.36499ceeca304b2f9ac4383ff712dda3&q=raghothams");
*/
result.mkString
}
def sleep(duration: Long) { Thread.sleep(duration) }
println("Hello Scala World")
// create a future which will make the API call
// Future is of type T
// so it expects the type as a param
// this also signifies the type returned by the future
val f : Future [String] = Future {
val res = getAPIResponse()
res
}
println("loling....")
// use the onComplete callback on the future f, to get the result
// the result can be success / failure
// handle response based on success / failure
f onComplete {
case Success(apiResponse) => println(apiResponse)
case Failure(t) => println("An error occured "+t.getMessage())
}
// keep JVM alive till future returns
sleep(4000)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment