我最近已将我的应用转换为继承here所述的猫的IOApp
。我阅读了该文档:
IOApp已经提供了Timer [IO]依赖项,因此 JVM不再需要隐式的ExecutionContext 在范围内
但是,我正在与其他一些需要使用ExecutionContext
的库(即http4s)进行交互。是否有推荐的方法来获取这种类型的应用程序?好的旧import scala.concurrent.ExecutionContext.Implicits.global
与提供的Timer[IO]
玩得很好吗?
答案 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
}
}