Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active June 25, 2023 15:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dacr/6e40f8239fa6828ab45a064b8131fdfc to your computer and use it in GitHub Desktop.
Save dacr/6e40f8239fa6828ab45a064b8131fdfc to your computer and use it in GitHub Desktop.
Simple akka hello world example / published by https://github.com/dacr/code-examples-manager #7e4e8d31-f6f0-494b-b609-8516b2277bb3/d36052d16920ac87d89ed05d9b98fb751ede14ff
// summary : Simple akka hello world example
// keywords : scala, actors, akka, helloworld, @testable
// publish : gist
// authors : David Crosson
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2)
// id : 7e4e8d31-f6f0-494b-b609-8516b2277bb3
// created-on : 2020-06-30T15:26:28Z
// managed-by : https://github.com/dacr/code-examples-manager
// run-with : scala-cli $file
// ---------------------
//> using scala "3.3.0"
//> using dep "com.typesafe.akka::akka-actor:2.6.21"
// ---------------------
import scala.concurrent.{ExecutionContextExecutor, Await}
import scala.concurrent.duration.Duration
import akka.actor.{Actor, ActorRef, ActorSystem, PoisonPill, Props, Terminated}
// import akka.pattern.ask // Required to get responses using ? (but take care, of course...)
// ---------------------------------------------------------------------------
object A {
case class Start()
case class AMsg(txt:String)
def props(b: ActorRef) = Props(new A(b))
}
class A(b: ActorRef) extends Actor {
override def receive = {
case A.Start() =>
b ! B.BMsg("hello world")
//sender ! "OK"
case A.AMsg(txt) =>
println(s"B says $txt")
context.system.terminate()
case x =>
println(s"Unsupported message received $x")
}
}
// ---------------------------------------------------------------------------
object B {
case class BMsg(txt:String)
def props() = Props(new B())
}
class B() extends Actor {
override def receive = {
case B.BMsg(txt) =>
sender() ! A.AMsg(s"message size is ${txt.size} for $txt")
}
}
// ---------------------------------------------------------------------------
object Toto {
val system = ActorSystem("HalSystem")
//implicit val executionContext: ExecutionContextExecutor = system.dispatcher
val b = system.actorOf(B.props())
val a = system.actorOf(A.props(b))
a ! A.Start()
//val rcf = (a ? A.Start()) (Timeout(10, TimeUnit.SECONDS))
//rcf.foreach(rc => println(rc))
}
Toto.system // Just to boot as object inits (statics) are lazy
Await.result(Toto.system.whenTerminated, Duration.Inf)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment