Last active
May 25, 2024 08:38
-
-
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/2044936e4a777a72b3987d999e2a9022edabe4e9
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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.4.2" | |
//> 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