zella
zella

Reputation: 4685

How to implement receive function outside actor scope and pass it to actor

I have an actor, that can be in several states. Initial state should be passed from outside:

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
}

I need to set initial state connected or authorized in constructor. Of course it may be some other function. But i don't understand how to achieve this:

new MyActor("id", ???)

Upvotes: 0

Views: 99

Answers (1)

joesan
joesan

Reputation: 15435

I see two possibilities

  1. Have the state passed in to the preStart lifecycle method of the actor

or

  1. Have an object companion that can be used to pass the state when initialising the actor instance. Something in the lines of:

    object MyActor {

    def props(initialState: YourState) = Props.actorOf(new MyActor(initialState))

    }

Also the initial state in your example need not be a partial function. You could model that as a case class and just use context.become to move between the states as they evolve.

EDIT: Adding an example to be a bit more clear!

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
  }
}

Upvotes: 2

Related Questions