Chaitanya
Chaitanya

Reputation: 3638

Akka Http actor injection in trait

I have a object that extends App wherein I create the Actor System and the Actor Materializer and also create an actor under the given actor system.

object QuickstartServer extends App with UserRoutes {

  implicit val system: ActorSystem = ActorSystem("helloAkkaHttpServer")
  implicit val materializer: ActorMaterializer = ActorMaterializer()

  val userRegistryActor: ActorRef = system.actorOf(UserRegistryActor.props, "userRegistryActor")


   lazy val routes: Route = userRoutes
      Http().bindAndHandle(routes, "localhost", 8080)
    }

Now UserRoutes contains all the routes

trait UserRoutes extends JsonSupport {

  implicit def system: ActorSystem
  lazy val log = Logging(system, classOf[UserRoutes])
  def userRegistryActor: ActorRef

  lazy val userRoutes: Route =
    pathPrefix("users") {
      concat(
        pathEnd {
          concat(
            get {
              val users: Future[Users] =
                (userRegistryActor ? GetUsers).mapTo[Users]
//Remaining code 

Now my question is that how is Actor System and the userRegistryActor actor that was created in QuickstartServer injected in the routes file ?

You can find the complete code here https://developer.lightbend.com/guides/akka-http-quickstart-scala/backend-actor.html

Upvotes: 1

Views: 134

Answers (1)

C4stor
C4stor

Reputation: 8026

At the beginning of the trait, you can see those two declarations :

  implicit def system: ActorSystem
  def userRegistryActor: ActorRef

Those two are abstract declarations in the trait, meaning that implementations of the trait have to provide those two.

That's what's happening in the object, with these two declarations :

 implicit val system: ActorSystem = ActorSystem("helloAkkaHttpServer")
 val userRegistryActor: ActorRef = system.actorOf(UserRegistryActor.props, "userRegistryActor")

A fair share of developers recommend making this kind of implementation more explicit by adding the override keyword, like this :

 override implicit val system: ActorSystem = ActorSystem("helloAkkaHttpServer")
 override val userRegistryActor: ActorRef = system.actorOf(UserRegistryActor.props, "userRegistryActor")

Upvotes: 3

Related Questions