Search code examples
scalasbtakkaakka-actor

how t send message to actor from sbt shell


I created a simple app with remote actor (example from here) :

object HelloRemote extends App  {
  val system = ActorSystem("HelloRemoteSystem")
  val remoteActor = system.actorOf(Props[RemoteActor], name = "RemoteActor")
  remoteActor ! "The RemoteActor is alive"
}

class RemoteActor extends Actor {
  def receive = {
    case msg: String =>
        println(s"RemoteActor received message '$msg'")
        sender ! "Hello from the RemoteActor"
  }
}

is it possible to send to it message from sbt shell ?


Solution

  • Only an actor reference is required to send messages to the Actor. e.g. You can do the same in the scala shell: Follow these:

    import akka.actor._
    

    Define your Actor in the shell.

    class RemoteActor extends Actor {
            def receive = {
              case msg: String =>
                  println(s"RemoteActor received message '$msg'")
                  sender ! "Hello from the RemoteActor"
            }
            }
    
    val system = ActorSystem("HelloRemoteSystem")
    val remoteActor = system.actorOf(Props[RemoteActor], name = "RemoteActor")
    remoteActor ! "The RemoteActor is alive"
    

    Here remoteActor is the reference for the Actor instantiated. You can send messages from anywhere if 1. This is actor is alive and 2. Your are able to acuire an actor reference there.