Play Framework 2.1 - Cannot find an implicit Execu

2019-03-08 23:16发布

问题:

I am calling a webservice like this:

WS
  .url(url)
  .get
  .map { response => // error occurs on this line
    response.status match {
      case 200 => Right(response.json)
      case status => Left(s"Problem accessing api, status '$status'")
  }
}

The complete error: Error: Cannot find an implicit ExecutionContext, either require one yourself or import ExecutionContext.Implicits.global

回答1:

According to this issue, it is fixed in the documentation. I needed to add the following import:

import play.api.libs.concurrent.Execution.Implicits._


回答2:

Since Play 2.4 you can inject default execution context via Guice dependency: injection.

class Foo @Inject()()(implicit ec:ExecutionContext) {

def bar() = {
   WS.url(url)
     .get
     .map { response => // error occurs on this line
       response.status match {
         case 200 => Right(response.json)
         case status => Left(s"Problem accessing api, status '$status'")
     }
   }
}


回答3:

An alternative option:

import scala.concurrent.ExecutionContext.Implicits.global