From 34c0837388b45c4b41eeeea069d1452bef558361 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aur=C3=A9lien=20Thieriot?= Date: Fri, 17 Mar 2017 13:47:08 +0000 Subject: [PATCH] Change `Unmarshal#to` to use a default context #78 (#947) * Change `Unmarshal#to` to use a default context #78 * Update Unmarshal.scala --- .../http/scaladsl/unmarshalling/Unmarshal.scala | 9 ++++++++- .../docs/http/scaladsl/UnmarshalSpec.scala | 17 ++++++++++++++++- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/akka-http/src/main/scala/akka/http/scaladsl/unmarshalling/Unmarshal.scala b/akka-http/src/main/scala/akka/http/scaladsl/unmarshalling/Unmarshal.scala index 82cad1d341f..c66debcfcf5 100644 --- a/akka-http/src/main/scala/akka/http/scaladsl/unmarshalling/Unmarshal.scala +++ b/akka-http/src/main/scala/akka/http/scaladsl/unmarshalling/Unmarshal.scala @@ -15,6 +15,13 @@ object Unmarshal { class Unmarshal[A](val value: A) { /** * Unmarshals the value to the given Type using the in-scope Unmarshaller. + + * Uses the default materializer [[ExecutionContext]] if no implicit execution context is provided. + * If you expect the marshalling to be heavy, it is suggested to provide a specialized context for those operations. */ - def to[B](implicit um: Unmarshaller[A, B], ec: ExecutionContext, mat: Materializer): Future[B] = um(value) + def to[B](implicit um: Unmarshaller[A, B], ec: ExecutionContext = null, mat: Materializer): Future[B] = { + val context: ExecutionContext = if (ec == null) mat.executionContext else ec + + um(value)(context, mat) + } } diff --git a/docs/src/test/scala/docs/http/scaladsl/UnmarshalSpec.scala b/docs/src/test/scala/docs/http/scaladsl/UnmarshalSpec.scala index ffe9c0e9d4b..63ec334850e 100644 --- a/docs/src/test/scala/docs/http/scaladsl/UnmarshalSpec.scala +++ b/docs/src/test/scala/docs/http/scaladsl/UnmarshalSpec.scala @@ -12,7 +12,7 @@ class UnmarshalSpec extends AkkaSpec { "use unmarshal" in { //#use-unmarshal import akka.http.scaladsl.unmarshalling.Unmarshal - import system.dispatcher // ExecutionContext + import system.dispatcher // Optional ExecutionContext (default from Materializer) implicit val materializer: Materializer = ActorMaterializer() import scala.concurrent.Await @@ -28,4 +28,19 @@ class UnmarshalSpec extends AkkaSpec { //#use-unmarshal } + "use unmarshal without execution context" in { + import akka.http.scaladsl.unmarshalling.Unmarshal + implicit val materializer: Materializer = ActorMaterializer() + + import scala.concurrent.Await + import scala.concurrent.duration._ + + val intFuture = Unmarshal("42").to[Int] + val int = Await.result(intFuture, 1.second) // don't block in non-test code! + int shouldEqual 42 + + val boolFuture = Unmarshal("off").to[Boolean] + val bool = Await.result(boolFuture, 1.second) // don't block in non-test code! + bool shouldBe false + } }