当前位置: 动力学知识库 > 问答 > 编程问答 >

scala - Access to ExecutionContext

问题描述:

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.

网友答案:

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." }
  }
}
网友答案:

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." }
  }
分享给朋友:
您可能感兴趣的文章:
随机阅读: