Search code examples
scalaakkaactorspraytraits

Getting access to an existing ActorSystem inside a trait


I'm using Spray for REST endpoints. How can I get access to an existing ActorSystem inside a trait?
I don't want to create a new ActorSystem inside my trait (if possible) but rather reuse my existing ActorSystem. I'm using this Redis client library.

trait MySprayService extends HttpService with Json4sSupport {

   //the following line requires an implicit ActorSystem 
   val redis = RedisClient(ip,port) 
   ....
   ....
   val simpleRoute = path("simple" / "route") {
       get {
          complete {
             //use Redis here
          }
       }
   }

}

Solution

  • You can create abstract method which returns ActorSystem and then deliver implementation in a class which will extends this trait.

    trait MySprayService extends HttpService with Json4sSupport {
    
           implicit def as: ActorSystem 
           //the following line requires an implicit ActorSystem 
           val redis = RedisClient(ip,port) 
           ....
           ....
           val simpleRoute = path("simple" / "route") {
               get {
                  complete {
                     //use Redis here
                  }
               }
           }
    
        }