Instantly share code, notes, and snippets.

Embed
What would you like to do?
package point
import akka.actor.{Actor, ActorRef, ActorSystem, Props}
import point.MainActor.Start
import point.Point.{Distance, DistanceResult}
import scala.concurrent.Await
import scala.concurrent.duration._
object MainActor {
def props(pointRef1: ActorRef, pointRef2: ActorRef): Props = Props(new MainActor(pointRef1, pointRef2))
case object Start
}
class MainActor(pointRef1: ActorRef, pointRef2: ActorRef) extends Actor {
override def receive: Receive = {
case Start =>
pointRef1 ! Distance(pointRef2) // !メソッドは、tellメソッドの別名!
case DistanceResult(value) =>
println(s"result = $value")
}
}
object Main extends App {
val system: ActorSystem = ActorSystem()
val pointRef1: ActorRef = system.actorOf(Point.props(1, 1))
val pointRef2: ActorRef = system.actorOf(Point.props(2, 2))
val mainRef: ActorRef = system.actorOf(MainActor.props(pointRef1, pointRef2))
// pointRef.x pointRef.yはコンパイルエラー
// pointRef.state にもアクセスできない
// そもそもActorRefからはActorの内部状態にアクセスできない
mainRef ! Start
sys.addShutdownHook {
system.terminate()
Await.result(system.whenTerminated, 60 seconds)
}
}
package point
import akka.actor.{Actor, ActorRef, Props}
import point.Point.{Distance, DistanceResult, GetPoint, GetPointResult}
object Point {
def props(x: Double, y: Double): Props = Props(new Point(x, y))
case class Distance(pointRef: ActorRef)
case class DistanceResult(value: Double)
private case object GetPoint
private case class GetPointResult(x: Double, y: Double)
}
class Point(val x: Double, val y: Double) extends Actor { // 本来 val は不要
// val state: State = ...
override def receive: Receive = {
case GetPoint =>
sender() ! GetPointResult(x, y)
case Distance(pointRef) =>
context.become(waitingPointResult(sender()))
pointRef ! GetPoint
}
private def waitingPointResult(_sender: ActorRef): Receive = {
case GetPointResult(x, y) =>
val dx = this.x - x
val dy = this.y - y
_sender ! DistanceResult(Math.sqrt(dx * dx + dy * dy))
context.unbecome()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment