我有一个演员,可以在几个州。初始状态应该从外部传递:
class MyActor(openId: String, initialState: Receive) extends Actor {
val connected: (String) => Receive = (openId: String) => {
case AuthorizedOk(user) => context.become(authorized(user))
...
case message => unhandled(message)
}
val authorized: (IUserInfo) => Receive = (user: IUserInfo) => {
case SomeLogic => context.become(...)
case message => unhandled(message)
}
def receive: Actor.Receive = initialState
}
我需要在构造函数中设置初始状态connected
或authorized
。当然它可能是其他一些功能。但我不明白如何实现这一目标:
new MyActor("id", ???)
答案 0 :(得分:2)
我看到两种可能性
或
在初始化actor实例时,有一个可用于传递状态的对象伴随。有些东西:
对象MyActor {
def props(initialState:YourState)= Props.actorOf(new MyActor(initialState))
}
此示例中的初始状态也不必是部分函数。您可以将其建模为案例类,并使用context.become在状态发生时在各个状态之间移动。
编辑:添加一个示例以使其更清晰!
sealed trait State
case object Authorized extends State
case object UnAuthorized extends State
class MyActor(state: State) extends Actor {
def receive: Receive = {
case state: State =>
// do some logic
val newState = someLogic(state)
// evolve with the new state
context.become(active(newState))
}
def active(newState: State): Receive = {
// do the pattern matching on the state and evolve
}
override def preStart(): Unit = {
super.preStart()
// send the initial state to this actor
self ! state
}
}