Skip to content

Instantly share code, notes, and snippets.

@chbatey
Last active December 7, 2017 10:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chbatey/d20e7c3c298dd2f00c429a3244004ca1 to your computer and use it in GitHub Desktop.
Save chbatey/d20e7c3c298dd2f00c429a3244004ca1 to your computer and use it in GitHub Desktop.
package info.batey.akka.persistence
import akka.actor.{ActorSystem, Props}
import akka.persistence.PersistentActor
import info.batey.akka.persistence.AlwaysPersist.RealPersistentActor.PrintName
object AlwaysPersist extends App {
trait AlwaysPersist extends PersistentActor {
val persistPredicate: Any => Boolean
final override def receive = receiveCommand
override def receiveCommand: Receive = {
case cmd if persistPredicate(cmd) => persist(cmd) { evt =>
postPersistHandler(evt)
}
case cmd =>
postPersistHandler(cmd)
}
def postPersistHandler(evt: Any): Unit
}
object RealPersistentActor {
case class PrintName(name: String)
}
class RealPersistentActor(val persistenceId: String) extends AlwaysPersist {
override def receiveRecover = {
case PrintName(name) =>
println(s"recovering $name")
case msg =>
println(s"Other kinds of msg: $msg")
}
override def postPersistHandler(evt: Any): Unit = evt match {
case PrintName(name) =>
println(s"Already been persisted by AlwaysPersist, now I just print the name: $name")
}
override val persistPredicate = {
case _:PrintName => true
case _ => false
}
}
val system = ActorSystem()
val pa = system.actorOf(Props(new RealPersistentActor("p1")))
pa ! PrintName("bella")
pa ! PrintName("ruby")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment