Skip to content

Instantly share code, notes, and snippets.

@DhavalDalal
Last active April 12, 2019 07:06
Show Gist options
  • Save DhavalDalal/6751d80def0547ac71ec889e98430cf0 to your computer and use it in GitHub Desktop.
Save DhavalDalal/6751d80def0547ac71ec889e98430cf0 to your computer and use it in GitHub Desktop.

Geographic Services (Scala)

Refer to GeographicService.scala. The code fetches Weather and nearby places information (both http calls to an end-point) and merges the 2 end-points responses to produce meaningful information as JSON string.

  • Part 1
    • Use Future’s flatMap to get the aggregate result.
    • Re-write the same using for-comprehension.
    • In each case strive to use minimal variables.
    • Measure time taken in each case and compare the results. You may use the time function provided therein.
  • Part 2
    • Running futures one after another turned out to be the same which the earlier sequential code was doing. By using Futures, we simply converted synchronous calls to asynchronous ones, devoid of any speed benefit.
    • Your task is to make this as fast as possible by running the futures in parallel. Make necessary modifications to both the versions of your earlier code.
    • Measure time taken in each case and compare the results and also with Part 1 cases.
import scala.concurrent.{Future, Await}
import scala.concurrent.duration._
import scala.language.postfixOps
def time[T](f: Future[T], timeout: Duration = 5 seconds) = {
val startTime = System.currentTimeMillis
val result = Await.result(f, timeout)
val diff = System.currentTimeMillis - startTime
println(s"Time Taken = $diff(ms).")
result
}
def getRequestData(url: String): String = io.Source.fromURL(url).mkString.trim
val host = "https://geographic-services.herokuapp.com"
val nearbyPath = "/places/nearby"
val weatherPath = "/weather"
// Mumbai Geo-loc
val lat = "lat=19.01"
val lon = "lon=72.8"
// Lord's Cricket Ground, London
// val lat = "lat=51.53"
// val lon = "lon=-0.17"
val radius = "radius=25"
val units = "unit=km"
val placesNearbyUrl = s"$host$nearbyPath?$lat&$lon&$radius&$units"
val placesNearbyData = getRequestData(placesNearbyUrl)
val weatherUrl = s"$host$weatherPath?$lat&$lon"
val weatherData = getRequestData(weatherUrl)
val weatherAndPlacesNearby = s"""{ "weather" : $weatherData, "placesNearby": $placesNearbyData }"""
println(weatherAndPlacesNearby)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment