13.5. Starting an Actor

Problem

You want to start an Akka actor, or attempt to control the start of an actor.

Solution

This is a bit of a tricky problem, because Akka actors are started asynchronously when they’re passed into the actorOf method using a Props. At the ActorSystem level of your application, you create actors by calling the system.actorOf method. Within an actor, you create a child actor by calling the context.actorOf method.

As demonstrated in Recipe 13.1, you can create an actor at the ActorSystem level by passing your actor class name (such as HelloActor) to the system.actorOf method, using the Props case class:

val system = ActorSystem("HelloSystem")

// the actor is created and started here
val helloActor = system.actorOf(Props[HelloActor], name = "helloactor")

helloActor ! "hello"

The process of creating a child actor from within another actor is almost identical. The only difference is that you call the actorOf method on the context object instead of on an ActorSystem instance. The context object is implicitly available to your actor instance:

class Parent extends Actor {
  val child = context.actorOf(Props[Child], name = "Child")
  // more code here ...
}

Discussion

The following complete example demonstrates how to create actors both at the system level and from within another actor:

package actortests.parentchild

import akka.actor._

case class CreateChild (name: String)
case class Name (name: String)

class Child extends Actor {
  var name = "No name"
  override def postStop ...

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.