Created
August 15, 2018 21:42
-
-
Save j5ik2o/b4512b2e2e6b5343ee8ac06cdb16aa90 to your computer and use it in GitHub Desktop.
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
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) | |
} | |
} |
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
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