Execute a future returning function on list of elements without failing in scala futures

Viewed 73

I am in weird situation of futures , I have this function call executeCall which returns a Future.failed(new Exception("Rts script failed ")) or Future.successful(this) now I am calling this function on a list of string like example shown below Now I have 2-3 scenarios which I want to understand in the sample code below

  1. when executeCall is called on elements of elems then it can either fail or get successful , what I want is that if executing that function returns an failure keep executing the executeCall on other elements but in the end execute function should be failed if any of the element fails .
  2. When executeCall is called on the elments and any of the element returns failure , then code should be sudden exited
  3. If i use the case 1 mentioned as shown below then in that case my code execution get sudden stopped if any of the elem fails
  4. If i use the case 2 , code never fails even when some elem return failure not able to understand why not
  5. Correct me on this question . Firstly we are trying to recover any exception thrown from the the end of executeCall but after recovering it we are converting it into our own exception and then we are storing the response into a variable
  6. Correct me on this . In case 2 when we use up a underscore what does it check
val elems = Seq("elem1" , "elem2" , "elem3" )
def execute(ctx ): Future[MyContext] = {

    val result = elems.map {
      script => {
        executeCall(script)
          .recoverWith { case e =>
            logger.error(e, s"Failed to execute [${script}] RTS script")
            throw MyOwnException(s"Failed to execute RTS script", e)
          }
      }
    }

// case 1
    Future(ctx) 
// case 2
   Future.sequence(result)
      .map(_ => ctx)


0 Answers
Related