我有一个有某些背景的演员,即
def step2: Receive = {
case _ => log error "Unhandled message"
}
def step1: Receive = {
case _ => log error "Unhandled message"
}
有没有办法知道演员当前处于哪个州(step1,step2)?
(我可以在string
上存储值,但我想知道是否有更好的方法。)
如果不可能,我想理解为什么因为这个状态应该保留在某个地方。
答案 0 :(得分:2)
您可以使用FSM
。 stateName
给出了州名。
使用在每个状态中处理的特殊消息对Actor进行Ping操作以发送stateName。
sealed trait ExampleState
case object State1 extends ExampleState
case object State2 extends ExampleState
case object C extends ExampleState
import akka.actor.{Actor, FSM}
import akka.event.EventHandler
import akka.util.duration._
case object Move
class ABC extends Actor with FSM[ExampleState, Unit] {
import FSM._
startWith(State1, Unit)
when(State1) {
case Ev(Move) =>
EventHandler.info(this, "Go to B and move on after 5 seconds")
goto(state2) forMax (5 seconds)
}
when(State2) {
case Ev(StateTimeout) =>
EventHandler.info(this, "Moving to C")
goto(C)
}
when(C) {
case Ev(Move) =>
EventHandler.info(this, "Stopping")
stop
}
initialize // this checks validity of the initial state and sets up timeout if needed
}
Akka Actor不存储有关PartialFunction的任何特定信息。所以我认为没有一个akka lib功能可以随时使用。
在actor中有state
,然后在Actor尝试成为某个东西时更新状态。
class FooBar extends Actor with ActorLogging {
var state: Option[String] = Some("receive")
override def receive: Receive = {
case _ => context become state1()
}
def state1: () => Receive = {
() => {
state = Some("state1")
{
case _ => log error "ignore"
}
}
}
def state2: () => Receive = {
() => {
state = Some("state2")
{
case _ => log error "ignore"
}
}
}
}