【问题标题】:How convert Cats Effect 3 to Future如何将 Cats Effect 3 转换为 Future
【发布时间】:2022-06-15 20:18:14
【问题描述】:

我正在尝试将 Playframework 与 Cats Effect 3 Tagless Final 样式相结合。

我被困在向未来的转变上。 Play 的 Action 需要我想要达到的值或 Future 来进行异步处理。

def method = authed { _ => 
  val program: EitherT[IO, Throwable, Int] = ???
  program
}

def authed[F[_]: Async](fa: Request => F[Result]): Action = {
 ???
}

在猫效应 2 中,可以通过 _.toIO.unsafeToFuture 实现,但现在已更改。 根据文档,我必须使用Dispatcher。找到了最初的想法on Github,但新的签名是F[Future[A]]

def beforeF[F[_]: Effect, A](fa: F[A]): Future[A] = fa.ioIO.unsafeToFuture()
// Note: Using a `Dispatcher` resource is cheap - don't worry about it
def preferredAfterF[F[_]: Async, A](fa: F[A]): F[Future[A]] = Dispatcher[F].use(_.unsafeToFuture(fa))

有人成功了吗?

【问题讨论】:

  • 问题是你试图为每个请求创建一个Dispatcher,这是错误的,你应该只创建一个并将它传递到你需要的地方,这样你就只有一个@ 987654328@。现在,如果您能够使用IOApp,那么您应该能够在那里创建调度程序并将其与所有其他依赖项结合起来,如果不能,那么您需要在创建调度程序时调用unsafeRunSync()

标签: scala playframework cats-effect tagless-final


【解决方案1】:

构建您的路由,以便它们可以访问 Disptacher 对象作为依赖项,那么生命周期将是适当的

class MyRoute[F[_]: MonadThrow](disp: Dispatcher[F]) {
  def method = authed { _ => 
    val program: EitherT[IO, Throwable, Int] = ???
    disp.unsafeToFuture(program.value)
  }
}

(这可能需要在Dispatcher[IO] 资源上使用allocatedIORuntime 的unsafeRunSync,具体取决于您的应用程序的连接方式)

【讨论】:

    猜你喜欢
    • 2021-12-28
    • 2021-04-20
    • 1970-01-01
    • 2017-01-27
    • 2021-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多