Suppose I want to aggregate data from 2 remote services, and serve response as fast as I can:
def loadUser: Future[User]
def loadData: Future[Data]
case class Payload(user: User, data: Data)
I understand that this one executes async tasks sequentially:
for {
user <- loadUser
data <- loadData
} yield Payload(user,data)
While this one executes them in parallel because async tasks are triggered before being sequentially chained:
val userF = loadUser
val dataF = loadData
for {
user <- userF
data <- dataF
} yield Payload(user,data)
The difference is however a bit too implicit for me and someone may not notice it at first.
Applicatives also solves the job
(loadUser |@| loadData) { Payload(_,_) }
Can someone tell me what I'd rather use between applicatives and monads to perform parallel async computation? What are the pros and cons of each approach?