4

我有这个特质

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)     
}

我想访问ExecutionContext像这样的另一个特征

trait AsyncGoodness extends NonBlockingGoodness {
  import akka.dispatch.Future

  def doSomething = {
    Future { "Future is the bomb." }
  }

但是,我收到了错误

Could not find implicit value for parameter executor: akka.dispatch.ExecutionContext

更新: 我想出了如何获得ExecutionContext范围

trait AsyncGoodness extends NonBlockingGoodness {
  import akka.dispatch.ExecutionContext
  import akka.dispatch.Future

  def doSomething()(implicit executor: ExecutionContext) = {
    Future { "Future is the bomb." }
  }

但是,我有一个后续问题。由于我可能有不止一种方法AsyncGoodness使用ExecutionContext,有没有办法在trait级别而不是像我上面所做的那样在每个方法中传递它。

4

2 回答 2

2

我知道你宁愿不必导入任何额外的东西,但这样的东西应该适合你。

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." }
  }
}
于 2012-10-22T03:57:25.803 回答
0

事实证明,我需要做的就是明确指定ec编译器使用它的返回类型。这是工作代码

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." }
  }
于 2012-10-22T23:31:43.173 回答