2013-02-22 14:13:32 +01:00
|
|
|
/**
|
2015-03-07 22:58:48 -08:00
|
|
|
* Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com>
|
2013-02-22 14:13:32 +01:00
|
|
|
*/
|
|
|
|
|
package docs.actor
|
|
|
|
|
|
|
|
|
|
import akka.actor.{ Props, Actor }
|
|
|
|
|
import akka.testkit.{ ImplicitSender, AkkaSpec }
|
|
|
|
|
|
|
|
|
|
object InitializationDocSpec {
|
|
|
|
|
|
|
|
|
|
class PreStartInitExample extends Actor {
|
|
|
|
|
override def receive = {
|
2013-12-03 16:34:26 +01:00
|
|
|
case _ => // Ignore
|
2013-02-22 14:13:32 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
//#preStartInit
|
|
|
|
|
override def preStart(): Unit = {
|
|
|
|
|
// Initialize children here
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Overriding postRestart to disable the call to preStart()
|
|
|
|
|
// after restarts
|
|
|
|
|
override def postRestart(reason: Throwable): Unit = ()
|
|
|
|
|
|
|
|
|
|
// The default implementation of preRestart() stops all the children
|
|
|
|
|
// of the actor. To opt-out from stopping the children, we
|
|
|
|
|
// have to override preRestart()
|
|
|
|
|
override def preRestart(reason: Throwable, message: Option[Any]): Unit = {
|
|
|
|
|
// Keep the call to postStop(), but no stopping of children
|
|
|
|
|
postStop()
|
|
|
|
|
}
|
|
|
|
|
//#preStartInit
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
class MessageInitExample extends Actor {
|
|
|
|
|
//#messageInit
|
|
|
|
|
var initializeMe: Option[String] = None
|
|
|
|
|
|
|
|
|
|
override def receive = {
|
2013-12-03 16:34:26 +01:00
|
|
|
case "init" =>
|
2013-02-22 14:13:32 +01:00
|
|
|
initializeMe = Some("Up and running")
|
|
|
|
|
context.become(initialized, discardOld = true)
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
def initialized: Receive = {
|
2014-01-16 15:16:35 +01:00
|
|
|
case "U OK?" => initializeMe foreach { sender() ! _ }
|
2013-02-22 14:13:32 +01:00
|
|
|
}
|
|
|
|
|
//#messageInit
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
class InitializationDocSpec extends AkkaSpec with ImplicitSender {
|
|
|
|
|
import InitializationDocSpec._
|
|
|
|
|
|
|
|
|
|
"Message based initialization example" must {
|
|
|
|
|
|
|
|
|
|
"work correctly" in {
|
|
|
|
|
val example = system.actorOf(Props[MessageInitExample], "messageInitExample")
|
|
|
|
|
val probe = "U OK?"
|
|
|
|
|
|
|
|
|
|
example ! probe
|
|
|
|
|
expectNoMsg()
|
|
|
|
|
|
|
|
|
|
example ! "init"
|
|
|
|
|
example ! probe
|
|
|
|
|
expectMsg("Up and running")
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|