Reputation: 8504
I have this trait
trait NonBlockingGoodness extends DataStore {
import akka.dispatch.{ Future, ExecutionContext }
import akka.util.duration._
import akka.util.Timeout
implicit val ec = ExecutionContext.fromExecutorService(yourExecutorServiceGoesHere)
implicit lazy val timeout = Timeout(5 seconds)
}
I would like to access the ExecutionContext
in another trait like such
trait AsyncGoodness extends NonBlockingGoodness {
import akka.dispatch.Future
def doSomething = {
Future { "Future is the bomb." }
}
However, I am getting the error
Could not find implicit value for parameter executor: akka.dispatch.ExecutionContext
UPDATED:
I figured out how to get the ExecutionContext
in scope
trait AsyncGoodness extends NonBlockingGoodness {
import akka.dispatch.ExecutionContext
import akka.dispatch.Future
def doSomething()(implicit executor: ExecutionContext) = {
Future { "Future is the bomb." }
}
However, I have a follow-up question. Since I may have more than 1 method in AsyncGoodness
that uses ExecutionContext
, is there a way to pass it in at the trait
level instead of at each method like I did above.
Upvotes: 4
Views: 9014
Reputation: 8504
As it turns out, all I need to do is explicitly specify ec
return type for the compiler to use it. Here's the working code
trait NonBlockingGoodness extends DataStore {
import akka.dispatch.{ Future, ExecutionContext }
import akka.util.duration._
import akka.util.Timeout
implicit val ec: ExecutionContext = ExecutionContext.fromExecutorService(yourExecutorServiceGoesHere)
implicit lazy val timeout = Timeout(5 seconds)
}
trait AsyncGoodness extends NonBlockingGoodness {
import akka.dispatch.Future
def doSomething = {
Future { "Future is the bomb." }
}
Upvotes: 0
Reputation: 906
I know you'd rather not have to import anything extra, but something like this should work for you.
trait NonBlockingGoodness {
import scala.concurrent.{ Future, ExecutionContext }
import scala.concurrent.util.duration._
import akka.util.Timeout
object Implicit {
implicit val ec = ExecutionContext.Implicits.global
implicit lazy val timeout = Timeout(5 seconds)
}
}
trait AsyncGoodness extends NonBlockingGoodness {
import scala.concurrent.Future
import Implicit._
def doSomething = {
Future { "Future is the bomb." }
}
}
Upvotes: 2