Skip to content

Instantly share code, notes, and snippets.

@yoeluk
Created January 7, 2019 15:53
Show Gist options
  • Save yoeluk/38a47970a2faea0b8aa9e86854d87bb8 to your computer and use it in GitHub Desktop.
Save yoeluk/38a47970a2faea0b8aa9e86854d87bb8 to your computer and use it in GitHub Desktop.
package com.ereactive.examples.akka.alarm
import akka.actor.typed.{ActorRef, Behavior}
import akka.actor.typed.scaladsl.Behaviors
import com.ereactive.examples.akka.alarm.Alarm._
class Alarm {
def anAlarm[S <: AlarmState](pinCode: Int, state: S = InactiveAlarm)
: Behavior[AlarmCommand] =
Behaviors.receiveMessage {
case ActivateAlarm(`pinCode`) =>
anAlarm(pinCode, ActivateAlarm)
case DeactivateAlarm(`pinCode`) =>
anAlarm(pinCode, InactiveAlarm)
case GetAlarmState(replyTo) =>
replyTo ! state
Behaviors.same
case LockAlarm(times) =>
val securityPinCode = ??? // get it from a database
lockedAlarm(securityPinCode) // doesn't compile
}
def lockedAlarm(securityPinCode: Int): Behavior[UnlockedAlarm] =
Behaviors.receive { (ctx, msg) => msg match {
case UnlockedAlarm(`securityPinCode`, newPinCode, replyTo) =>
replyTo ! InactiveAlarm(newPinCode)
anAlarm(newPinCode, InactiveAlarm) // doesn't compile
}}
}
object Alarm {
sealed trait AlarmCommand
case class ActivateAlarm(pinCode: Int) extends AlarmCommand
case class DeactivateAlarm(pinCode: Int) extends AlarmCommand
case class GetAlarmState(replyTo: ActorRef[AlarmState]) extends AlarmCommand
case class LockAlarm(incorrectPinCodeTimes: Int) extends AlarmCommand
case class UnlockedAlarm(securityPinCode: Int, newPinCode: Int, replyTo: ActorRef[InactiveAlarm.type]) extends AlarmCommand
sealed trait AlarmState
case object ActiveAlarm extends AlarmState
case object InactiveAlarm extends AlarmState
case object LockedAlarm extends AlarmState
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment