Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@yasuabe
Created December 19, 2017 06:26
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 yasuabe/c83ead2e76c93686c5da1c664b340863 to your computer and use it in GitHub Desktop.
Save yasuabe/c83ead2e76c93686c5da1c664b340863 to your computer and use it in GitHub Desktop.
by akka typed
// program 中のregisterの持ち回りを避ける
import akka.typed._
import akka.typed.scaladsl.Actor
import akka.typed.scaladsl.Actor.immutable
import cats.data.{ReaderT, WriterT}
import cats.effect.IO
import cats.instances.vector._
trait Command
final case class Purchase(amount: Int) extends Command
case object PrintTotal extends Command
object CashRegister {
def apply(total: Int): Behavior[Command] = behavior(total)
private def behavior(total: Int): Behavior[Command] = immutable {
case (_, Purchase(amount)) => println(amount); behavior(total + amount)
case (_, PrintTotal) => println(total); Actor.same
}
}
type PurchaseHistory = Vector[Purchase]
def execute(p: Purchase)
: ReaderT[WriterT[IO, PurchaseHistory, ?], ActorRef[Command], Unit] =
ReaderT { actor =>
WriterT.lift[IO, PurchaseHistory, Unit](IO { actor ! p }) tell Vector(p)
}
// test -------------------------------------------------------------------
val p1 = Purchase(100)
val p2 = Purchase(50)
def program = for {
_ <- execute(p1)
_ <- execute(p2)
} yield ()
val root = Actor.deferred[Nothing] { ctx =>
val register = ctx.spawn(CashRegister(0), "register1")
val (h, _) = program.run(register).run.unsafeRunSync()
register ! PrintTotal
//再実行
val register2 = ctx.spawn(CashRegister(10), "register2")
h.foreach(a => register2 ! a)
register2 ! PrintTotal
Actor.empty
}
ActorSystem[Nothing](root, "RegisterSample")
Thread.sleep(2000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment