gpt4 book ai didi

scala - scala cats IOApp 应该如何获取 ExecutionContext?

转载 作者:行者123 更新时间:2023-12-02 19:48:17 24 4
gpt4 key购买 nike

我最近将我的应用程序转换为继承猫的 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

关于scala - scala cats IOApp 应该如何获取 ExecutionContext?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58812223/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com