1

How to run in parallel the two different functions that returns different datatype?

Here we have fruitFutures, and primeFutures. How can I utilize the Await.result function?

val fruits = List("apple", "orange", "mango", "banana")
val primeNums = List(2,3,5,7,11)

def executeFruit(fruit: String): Try[String] = {
  Try {
   s"executed $fruit"
  }
}

def executePrime(prime: Int): Try[Int] = {
  Try {
    prime * 2
  }
}

val fruitFutures: List[Future[Try[String]]] = for {
     fruit <- fruits
   } yield {
     Future {
      executeFruit(fruit)
     }
   }

val primeFutures: List[Future[Try[Int]]] = for {
     prime <- primeNums
   } yield {
     Future {
      executePrime(prime)
     }
   }

val futureResults = Await.result(Future.sequence(???), Duration.Inf)
3
  • 1
    future.sequence(fruitFuture ++ primeFuture).map( //do your thing) Commented Mar 31, 2021 at 7:47
  • Thanks, but it's giving me Product with Serializable so not sure how to work with this. Commented Mar 31, 2021 at 7:59
  • 1
    Future[Try[..]] can hardly make sense Commented Mar 31, 2021 at 8:10

1 Answer 1

2

You can try this:

    val futureResults = for {
      f <- Future.sequence(fruitFutures)
      p <- Future.sequence(primeFutures)
    } yield (f, p)
    val (fruitResult, primeResult) =
      Await.result(futureResults, Duration.Inf)

This will result:

List(Success(executed apple), Success(executed orange), Success(executed mango), Success(executed banana))
List(Success(4), Success(6), Success(10), Success(14), Success(22))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.