1
votes

I want to implement I was looking at this example taken from typesafe activator (spray-actor-per-request)

class RestRouting extends HttpService with Actor with PerRequestCreator {

implicit def actorRefFactory: ActorContext = context

def receive = runRoute(route)

val petService = context.actorOf(Props[PetClient])
val ownerService = context.actorOf(Props[OwnerClient])

val route = {
 get {
   path("pets") {
          parameters('names) { names =>
    petsWithOwner {
           GetPetsWithOwners(names.split(',').toList)
     }
   }
  }
 }
}

def petsWithOwner(message : RestMessage): Route =
ctx => perRequest(ctx, Props(new GetPetsWithOwnersActor(petService, ownerService)), message)
}

and I wonder if this is the best parctice to implement the actors creation :

ctx => perRequest(ctx, Props(new GetPetsWithOwnersActor(petService, ownerService)), message)

because I saw at the akka documentation this warning regarding creating actor within an actor :

val props2 = Props(new ActorWithArgs("arg")) // careful, see below

also if we define an actor within an actor

val ownerService = context.actorOf(Props[OwnerClient])

how can it be tested ?

Just to make things clear - I am not criticizing, I am just trying to learn the best practice of implementation specially as I see the typesafe activator as educational source

1
You can create your actor in a companion object, which will ensure that you never close over any state of your parent actor. - Soumya Simanta

1 Answers

0
votes

Actors are arranged in a hieararchy starting from the root of an ActorSystem. For most even moderately complex projects all actors won't be created at that root but some actors will supervise others and hence create them. Such child actors can be tested with the Akka TestKit which extends ActorSytem to create a test ActorSystem that can substitute for a given parent actor and provides access to its children for testing. Examples of this are available in the book "Akka Concurrency" by Derek Wyatt. Specifically, this book has a plane simulation in which a Plane actor creates Pilot and CoPilot actors which are tested with the TestKit combined with ScalaTest as demonstrated in https://github.com/danluu/akka-concurrency-wyatt/blob/master/src/test/scala/PilotsSpec.scala. In order to do that the TestKit replaces the Plane and creates Pilot and CoPilot actors as its children. This is possible partly because the Pilot and CoPilot don't know who or what creates them. For reference see how the Plane creates them in https://github.com/danluu/akka-concurrency-wyatt/blob/master/src/main/scala/Plane.scala. This entire project works and provides a number of excellent examples of Akka usage. It can use some updating to remove deprecations and it will be necessary to correct scala.concurrent.util.duration to scala.concurrent.duration when compiling it with more recent versions of scala.