Daniel Wu
Daniel Wu

Reputation: 6003

actor:possible to send and receive nested in a receive

When process a message, is it possible to send out an message to another actor and wait for that actor to reply, and consume the replied message and then continue, like the following, is it doable?

val lineMap=HashMap[String,Int]()
receive {
   case bigTaskMap=> 
       for (line <-readSomeFile){
          if(lineMap.get(line)==None){
              anotherActor!line  // that actor will reply a hashmap which contain the key for line
              receive {
                 case x:HashMap => lineMap=x
              }     
          }
          lineMap.get(line) // use that value to do further work
       }
}

Upvotes: 0

Views: 216

Answers (1)

Robin Green
Robin Green

Reputation: 33063

This answer is for Akka (old Scala actors are deprecated in Scala 2.10).

Yes. You can use ask to get a future (rather than creating a fully-fledged actor yourself) and then call onComplete on the Future returned to set an action which will be executed when the Future's value (or an error) becomes available. Don't worry about how quickly the Future might yield a value - it doesn't matter, because the onComplete action will be executed even if the Future is already available when onComplete is called!

However, be very careful: you should not directly access any of the state (i.e. the variables) in the containing actor in your action(s), because the onComplete action(s) will not run in the same execution context as the actor (i.e. they could be running at the same time as the original actor is processing a message). Instead, send further messages back to the original actor, or forward them on.

In fact, in some cases you may find the simplest thing to do is simply to send a message, and let the original actor handle the reply. become and unbecome may help here. However, again, be careful if using become, that in the actor's new behaviour, it doesn't drop "ordinary" messages that should be handled in the ordinary way.

Upvotes: 1

Related Questions