scala cats IOApp 应该如何获取 ExecutionContext?

How should a scala cats IOApp acquire an ExecutionContext?

我最近将我的应用转换为继承猫的 IOApp,如 here 所述。我在该文档中读到:

the Timer[IO] dependency is already provided by IOApp, so on top of the JVM there’s no longer a need for an implicit ExecutionContext to be in scope

但是,我正在与其他几个确实需要 ExecutionContext 的库(即 http4s)进行交互。在此类应用程序中是否有推荐的方法来获取一个?好的旧 import scala.concurrent.ExecutionContext.Implicits.global 与所提供的 Timer[IO] 配合得好吗?

尝试扩展特征 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