【问题标题】:High level of what I will need to do to port ReactiveMongo scala to use cats effects?我需要做些什么来移植 ReactiveMongo scala 以使用猫效果?
【发布时间】:2020-07-13 18:28:38
【问题描述】:

如果我想在 http4s 之类的东西中使用 ReactiveMongo,我必须将 ReactiveMongo 返回的所有 Future 调用包装在 Cats IO 效果中,这样说是否正确?

概括地说,将 ReactiveMongo 合并到 http4s 中需要哪些步骤?

【问题讨论】:

  • 简短回答:是的

标签: scala reactivemongo cats-effect


【解决方案1】:

Cats Effect 提供了 Async 类型类,它可以让你将一些回调(例如 Future 的 onComplete)转换为 F。一个example from documentation

import cats.effect.{IO, Async}

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

val apiCall = Future.successful("I come from the Future!")

val ioa: IO[String] =
  Async[IO].async { cb =>
    import scala.util.{Failure, Success}

    apiCall.onComplete {
      case Success(value) => cb(Right(value))
      case Failure(error) => cb(Left(error))
    }
 }

ioa.unsafeRunSync()

实际上,Async[F] evan 有一个方法允许将 Future 提升为异步:Async[F].fromFuture(Sync[F].defer(future))Future 被包裹在 IO 中,因为它的创建是有副作用的,并且会触发急切的计算)。

但是,如果您专门使用cats.effect.IO,则可以简单地使用IO.fromFuture(IO(future))

您必须在需要将 Future 转换为 IO(或其他 F)的任何地方使用这个(或一些委托给这个的实用程序)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-24
    • 2011-09-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-12
    • 1970-01-01
    • 2013-07-05
    相关资源
    最近更新 更多