futures
Placeholder object for value that may not yet exist, revolve around ExecutionContext which has access to a thread pool similar to Executor design pattern, commonly you map over it
val futureHttpResult = WS.url(“http://catpictures.dev/top10”).get()
val webPage = futureHttpResult.map { catPicturesHttpBody =>
val parsed = parse(catPicturesHttpBody)
val firstPictureUrl = parsed.get(0)
Ok(myWebPageTemplate(firstPictureUrl))
}
webPageNonblocking Looks sequential, but when it does load inner map block runs
Promises like syntax
val fut1: Future[Assignment] = Future(nextAssignmentStore.get(classId1))
val fut2: Future[Assignment] = Future(nextAssignmentStore.get(classId2))
val fut3: Future[Assignment] = Future(nextAssignmentStore.get(classId3))
val allFutures: List[Future[Assignment]] = List(fut1, fut2, fut3)Need Future[List[]] instead of List[Future[]]
then runs when all complete
val allResults: Future[List[Assignment]] = Future.sequence(allFutures)
allResults.map { results =>
Result(results, paging = None)
}Defining
Defining Global Execution Context
States
not yet completed, not completed
completed with value or exception, completed
failed with exception or successfully completed with value
Immutable after it becomes completed
Callbacks
Callback takes a Try[T] => U where Try[T] is like an option but contains either the variable or an exception
Combinators
Only Success (foreach)
Change Future Value (map)
exception are propagated
For comprehensions(flatmap & withfilter)
flatmap -> like map but ft returns a future not a value, used to call ft's that return future on value yet to be computed
for loop basically allows several flatMaps then a final map yielding a Future value
futures start running immediately on seperate threads and main thread runs through this without blocking
resultF is just a Future that waits for component parts to finish before completing itself
Example 2
Exception recovery
recover
RecoverWith
fallbackTo
Coursera Usage
future.flatMap(x =>
)
is the same as
x <- future
Thread blocks while the future waits to finish and collapse
y <- x
Last updated