user1491739
user1491739

Reputation: 1017

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.

Upvotes: 5

Views: 3188

Answers (1)

Andriy Plokhotnyuk
Andriy Plokhotnyuk

Reputation: 7989

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))

Upvotes: 9

Related Questions