SuperMacho SuperMacho -3 years ago 123
Scala Question

I want to send second message to Actor as new Message

I have two actors for example, sender:

class ActorSender(actroReciever: ActorRef) extends Actor{
implicit val timeout = Timeout(100, TimeUnit.SECONDS)

override def receive: Receive = {
case "RUN" => {
val resp = Await.result(actroReciever ? "Msg", 100.seconds)
println("receive response " + resp)
};
case str:String => println(str)
case _ => println("Error type msg")
}
}


reciever:

class ActroReciever extends Actor{
override def receive: Receive = {
case str:String => {
val snd = sender()
snd ! "MessageFirst"
snd ! "MessageSecond"
}
}
}


And class for starting:

object Tester extends App {
val system = ActorSystem("system")
val receiver = system.actorOf(Props[ActroReciever](new ActroReciever()), "receiver")
val sender = system.actorOf(Props[ActorSender](new ActorSender(receiver)), "sender")
sender ! "RUN"
}


I want to send two messages to sender(), first as reply for "ask", second msg as "new Message", which ActorSender execute as "matching", how I can do it? Thanks

Answer Source

First, you know you should not use Await, right?

Second, ask (?) is not meant to be used within actors. ask creates a temporary actor which can only receive a single message. It is not your ActorSender receiving the answer, but the temporary actor created by ask. That's why you have the feeling you can only send 1 answer.

You are doing this wrong, you should simply send your message using actroReciever ! "Msg". No need to change anything on your ActroReciever.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download