Is it ok to use mutable states with akka PersistentActor or shall I use context.become/unbecome
with receiveCommand() and not with the receiveRecover() as it will wait for the full recovery before the state is changed.
In general you can't use context.become
and friends within a PersistentActor
because those affect the receive
method, which is provided by the PersistentActor
(and handles some internal messages which are implementation details, so you don't really want to duplicate it).
Being more explicit about the mutable state than context.become
is a better path.
There is a pattern of wrapping up all the mutable state into a single immutable object (e.g. a Scala case class
) and deferring the command handling to that object, which could be as simple as something like:
var state: State = ???
override val receiveCommand: Receive = state.processCommand(_)
You can go further and have your processCommand
method on State
return, e.g. a (Seq[Event], () => Try[Unit])
... this is actually fairly close to what projects like Lagom or Typed Persistence are doing.