我最近将我的应用程序转换为继承cats的IOApp
,如下所述。我在文件中读到:
IOApp已经提供了Timer[IO]依赖项,因此JVM不再需要隐式ExecutionContext在范围内
但是,我正在与其他几个确实需要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)
}
}
或者对于来自具有固定线程数的线程池的CCD_ 7
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