Scala: How to deal with sequences in a Future for comprehension

554 views Asked by At

Given the following methods that return a Future...

def getProducts: Future[List[Product]] = { ... }
def sendOrder(p: Product, n: Int): Future[Order] = { ... }

... I need to invoke sendOrder for each product returned by getProducts and in the end yield the number of products processed:

for {
  products <- getProducts
  // how do I iterate thru products and invoke sendOrder for each element?
  ...
} yield products.length

How do I deal with the list of products in the for comprehension above?

EDIT

Things get even more complex since I need to invoke a third method before sendOrder if and only if getProducts actually returns a nonEmpty list:

def doSomethingBeforeSendingOrder: Future[String] = { ... }

for {
  p <- getProducts
  // how do I invoke doSomethingBeforeSendingOrder before sendOrder and
  // only if getProducts actually returns a nonEmptylist?
  o <- Future.sequence(p.map(senderOrder(_,IDontKnowWhatThisIntMeans)))
} yield o.length
1

There are 1 answers

1
melps On BEST ANSWER

I dont' know where that second arg to sendOrder should come from, but essentially you want to do something like:

for {
  p <- getProducts
  if p.nonEmpty
  _ <- someOtherMethodThatReturnsAFuture
  o <- Future.sequence(p.map(senderOrder(_,IDontKnowWhatThisIntMeans)))
} yield o.length

Future.sequence will turn your List[Future[Order]] into a Future[List[Order]]