Play Framework 2.1 - Cannot find an implicit ExecutionContext

ScalaPlayframeworkPlayframework 2.0

Scala Problem Overview


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

Scala Solutions


Solution 1 - Scala

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

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

Solution 2 - Scala

Since Play 2.6 it's recommended to use guice dependency injection for execution context.

Default execution context injection:

Foo.scala

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

Custom execution context injection:

application.conf

# db connections = ((physical_core_count * 2) + effective_spindle_count)
fixedConnectionPool = 9

database.dispatcher {
  executor = "thread-pool-executor"
  throughput = 1
  thread-pool-executor {
    fixed-pool-size = ${fixedConnectionPool}
  }
}

DatabaseExecutionContext.scala

@Singleton 
class DatabaseExecutionContext @Inject()(system: ActorSystem) extends CustomExecutionContext(system,"database.dispatcher")

Foo.scala

class Foo @Inject()(implicit executionContext: DatabaseExecutionContext ) {   ...    }

More info at:

https://www.playframework.com/documentation/2.6.x/Migration26#play.api.libs.concurrent.Execution-is-deprecated https://www.playframework.com/documentation/2.6.x/Highlights26#CustomExecutionContext-and-Thread-Pool-Sizing

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEECOLORView Question on Stackoverflow
Solution 1 - ScalaEECOLORView Answer on Stackoverflow
Solution 2 - ScalamgoskView Answer on Stackoverflow