斯卡拉猫IOApp应该如何获取ExecutionContext?

时间:2019-11-12 04:51:31

标签: scala scala-cats cats-effect

我最近已将我的应用转换为继承here所述的猫的IOApp。我阅读了该文档:

  IOApp已经提供了

Timer [IO]依赖项,因此   JVM不再需要隐式的ExecutionContext   在范围内

但是,我正在与其他一些需要使用ExecutionContext的库(即http4s)进行交互。是否有推荐的方法来获取这种类型的应用程序?好的旧import scala.concurrent.ExecutionContext.Implicits.global与提供的Timer[IO]玩得很好吗?

1 个答案:

答案 0 :(得分:2)

尝试扩展特征IOApp.WithContext。对于全局ExecutionContext

import cats.effect._
import scala.concurrent.ExecutionContext

object Main extends IOApp.WithContext {
  implicit val ec = ExecutionContext.global

  override protected def executionContextResource: Resource[SyncIO, ExecutionContext] =
    Resource.liftF(SyncIO(ec))

  def run(args: List[String]): IO[ExitCode] = {

    implicitly[Timer[IO]]
    implicitly[ContextShift[IO]]
    implicitly[ExecutionContext]

    IO.pure(ExitCode.Success)
  }
}

或对于ExecutionContext来自具有固定线程数的线程池

import java.util.concurrent.{Executors, TimeUnit}
import cats.effect._
import scala.concurrent.ExecutionContext

object Main extends IOApp.WithContext {
  override protected def executionContextResource: Resource[SyncIO, ExecutionContext] =
    Resource.make(SyncIO(Executors.newFixedThreadPool(8)))(pool => SyncIO {
      pool.shutdown()
      pool.awaitTermination(10, TimeUnit.SECONDS)
    }).map(ExecutionContext.fromExecutorService)

  def run(args: List[String]): IO[ExitCode] = {
    executionContextResource.use { implicit ec =>

      implicitly[Timer[IO]]
      implicitly[ContextShift[IO]]
      implicitly[ExecutionContext]

      SyncIO.pure(ExitCode.Success)
    }.toIO
  }
}

https://github.com/typelevel/cats-effect/issues/337

https://github.com/typelevel/cats-effect/pull/344