view src/main/scala/IncrementSample.scala @ 7:3b99f171603d default tip

add system.terminate()
author Takahiro SHIMIZU <anatofuz@cr.ie.u-ryukyu.ac.jp>
date Tue, 30 Jan 2018 13:35:32 +0900
parents 230a3627b7d7
children
line wrap: on
line source

package IncrementSample


import akka.actor.{Actor, ActorLogging, ActorRef, ActorSystem, Props, TypedActor}


object Incrementer {
  def props(printerActor:ActorRef): Props = Props(new Incrementer(printerActor))

  final case class SendData(data:Int)
  final case class SetActor(actor:ActorRef)
}

class Incrementer(printerActor: ActorRef) extends Actor {
  import  Incrementer._
  import  Printer._


  var otherActor = ActorRef.noSender
  val MAX_SIZE = 10

  def receive = {
    case SendData(data) =>
        printerActor ! Println(data.toString)
        if (data < MAX_SIZE) {
          val send_data = data + 1
          otherActor ! SendData(send_data)
        }
    case SetActor(actor :ActorRef) =>
      otherActor = actor
  }
}

object Printer {
  def props: Props = Props[Printer]

  final case class Println(message: String)
}

class Printer extends  Actor with ActorLogging {
  import Printer._

  def receive = {
    case Println(message) =>
      log.info(s"Printer received (from ${sender()} ): $message")
  }
}

object IncrementSample extends App {

  import Incrementer._


  val system: ActorSystem = ActorSystem("incrementSample")

  val printer: ActorRef = system.actorOf(Printer.props,"printerActor")

  val actorOne: ActorRef = system.actorOf(Incrementer.props(printer),"ActorOne")
  val actorTwo: ActorRef = system.actorOf(Incrementer.props(printer),"ActorTwo")

  actorOne ! SetActor(actorTwo)
  actorTwo ! SetActor(actorOne)

  val FIRST_DATA = 1

  actorOne ! SendData(FIRST_DATA)

  system.terminate()
}