hliu
hliu

Reputation: 1047

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 ?

Upvotes: 0

Views: 501

Answers (2)

psisoyev
psisoyev

Reputation: 2168

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
 }

Upvotes: 2

Ryan
Ryan

Reputation: 7247

This is what pipeTo is for:

import akka.pattern.pipe

...

doFuture.pipeTo(sender())

Upvotes: 2

Related Questions