DatabaseExecutionContext is missing from the Play API

Viewed 802

I am following the DB presription provided here. However, the class DatabaseExecutionContext is nowhere near to be found in the play API and, hence, I am unable to import it.

What am I missing?

2 Answers

See the example code here: https://github.com/playframework/play-samples/blob/2.8.x/play-scala-anorm-example/app/models/DatabaseExecutionContext.scala

import javax.inject._

import akka.actor.ActorSystem
import play.api.libs.concurrent.CustomExecutionContext

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

You need to configure this context as shown by the documentation: https://www.playframework.com/documentation/2.8.x/AccessingAnSQLDatabase#Using-a-CustomExecutionContext

While you already got an answer, I suggest to use a base trait instead, like:

import javax.inject.{Inject, Singleton}

import akka.actor.ActorSystem
import play.api.libs.concurrent.CustomExecutionContext

import scala.concurrent.ExecutionContext

trait DatabaseExecutionContext extends ExecutionContext

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

The reason is that if you don't, you'll need to bring akka while testing operations requiring this execution context, with the trait, you should be able to write a simple executor for your tests, like:

  implicit val globalEC: ExecutionContext = scala.concurrent.ExecutionContext.global

  implicit val databaseEC: DatabaseExecutionContext = new DatabaseExecutionContext {
    override def execute(runnable: Runnable): Unit = globalEC.execute(runnable)

    override def reportFailure(cause: Throwable): Unit = globalEC.reportFailure(cause)
  }

EDIT: I have created a detailed post explaining this.

Related