From 94e6884d7fe3372b9613260b7fa25bc0abf34961 Mon Sep 17 00:00:00 2001 From: Tushar Mathur Date: Wed, 26 Jan 2022 13:15:17 +0530 Subject: [PATCH] refactor: reduce allocations --- .../src/main/scala/zhttp/service/HttpRuntime.scala | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/zio-http/src/main/scala/zhttp/service/HttpRuntime.scala b/zio-http/src/main/scala/zhttp/service/HttpRuntime.scala index 7b8e6d8732..2d3e0888ab 100644 --- a/zio-http/src/main/scala/zhttp/service/HttpRuntime.scala +++ b/zio-http/src/main/scala/zhttp/service/HttpRuntime.scala @@ -14,21 +14,21 @@ import scala.jdk.CollectionConverters._ * cancel the execution when the channel closes. */ final class HttpRuntime[+R](strategy: HttpRuntime.Strategy[R]) { - def unsafeRun(ctx: ChannelHandlerContext)(program: ZIO[R, Throwable, Any]): Unit = { val rtm = strategy.getRuntime(ctx) // Close the connection if the program fails // When connection closes, interrupt the program - def closeListener(fiber: Fiber.Runtime[_, _]): GenericFutureListener[Future[_ >: Void]] = - (_: Future[_ >: Void]) => rtm.unsafeRunAsync_(fiber.interrupt): Unit rtm .unsafeRunAsync(for { fiber <- program.fork - close <- UIO(closeListener(fiber)) - _ <- UIO(ctx.channel().closeFuture.addListener(close)) + close <- UIO { + val close = closeListener(rtm, fiber) + ctx.channel().closeFuture.addListener(close) + close + } _ <- fiber.join _ <- UIO(ctx.channel().closeFuture().removeListener(close)) } yield ()) { @@ -41,6 +41,9 @@ final class HttpRuntime[+R](strategy: HttpRuntime.Strategy[R]) { if (ctx.channel().isOpen) ctx.close() } } + + private def closeListener(rtm: Runtime[Any], fiber: Fiber.Runtime[_, _]): GenericFutureListener[Future[_ >: Void]] = + (_: Future[_ >: Void]) => rtm.unsafeRunAsync_(fiber.interrupt): Unit } object HttpRuntime {