Search code examples
scalaakkaactor

Akka actor cannot send back the message


say, I have an Actor whose receive function likes

def receive = {
  case Message =>
    val doFuture: Future[String] = doSomething()

    doFuture onSuccess {
      case doResult =>
        //////////// Here is the problem !! /////////////
        // --> here fail. Seems sender cannot send back the result to the caller
        sender ! doResult
    }

    doFuture onFailure {
      // handle exception
    }
}

why the sender cannot send back message any more ?


Solution

  • def receive = {
      case Message =>
        val doFuture: Future[String] = doSomething()
        val requester = sender
    
        doFuture onSuccess {
          case doResult =>
            requester ! doResult
        }
    
        doFuture onFailure {
          // handle exception
        }
    }
    

    You can save your original sender and then use it (in case if you don't want to use pipe for some reason). Anyway, pipe looks much better and is specially designed for such cases:

    import akka.pattern.pipe
    
     def receive = {
          case Message =>
              val doFuture: Future[String] = doSomething()  
              doFuture pipeTo sender
     }