alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Akka/Scala example source code file (InitializationDocSpec.scala)

This example Akka source code file (InitializationDocSpec.scala) is included in my "Source Code Warehouse" project. The intent of this project is to help you more easily find Akka and Scala source code examples by using tags.

All credit for the original source code belongs to akka.io; I'm just trying to make examples easier to find. (For my Scala work, see my Scala examples and tutorials.)

Akka tags/keywords

actor, akka, ignore, initializationdocspec, messageinitexample, ok, option, test, testing, testkit, throwable, u, unit, up

The InitializationDocSpec.scala Akka example source code

/**
 * Copyright (C) 2009-2014 Typesafe Inc. <http://www.typesafe.com>
 */
package docs.actor

import akka.actor.{ Props, Actor }
import akka.testkit.{ ImplicitSender, AkkaSpec }

object InitializationDocSpec {

  class PreStartInitExample extends Actor {
    override def receive = {
      case _ => // Ignore
    }

    //#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 = {
      case "init" =>
        initializeMe = Some("Up and running")
        context.become(initialized, discardOld = true)

    }

    def initialized: Receive = {
      case "U OK?" => initializeMe foreach { sender() ! _ }
    }
    //#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")

    }

  }

}

Other Akka source code examples

Here is a short list of links related to this Akka InitializationDocSpec.scala source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.