Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala AKKA access variable or return a value

Here is my code:

class testActor extends Actor   {
    var test = "test2"
    def receive = {
            case "test" ⇒ 
                    test="works"
                    "works"

    }
}


 def test = Action {
    var test = "test"
    val system = ActorSystem("MySystem")
    val myActor = system.actorOf(Props[testActor.testActor], name = "testActor")

    myActor ! "test"

    test = myActor.test

Ok(views.html.test(test))
}

the line: test = myActor.test doesn't work.

I either need a way to access what is returned by the actor function, in this case "works", or a way to access a variable inside the Actor.

like image 703
user1491739 Avatar asked Jul 13 '12 20:07

user1491739


1 Answers

To return result to sender send a message to it back:

def receive = {
  case "test" => sender ! "works"
}

For waiting of response use Await.result() call:

  implicit val timeout = Timeout(Duration(1, TimeUnit.SECONDS))
  test = Await.result(myActor ? "test", Duration(1, TimeUnit.SECONDS))
like image 142
Andriy Plokhotnyuk Avatar answered Oct 05 '22 12:10

Andriy Plokhotnyuk