Search code examples
scalareactivemongocats-effect

High level of what I will need to do to port ReactiveMongo scala to use cats effects?


Is it correct to say that if I wanted to use ReactiveMongo in something like http4s I will have to wrap all the Future calls that ReactiveMongo returns in a Cats IO effect?

At a high level, what are the steps I would need to incorporate ReactiveMongo into http4s?


Solution

  • Cats Effect provides Async typeclass which let you translate some callback (e.g. Future's onComplete) into F. An 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()
    

    Actually, Async[F] evan has a method allowing to lift Future to async: Async[F].fromFuture(Sync[F].defer(future)) (Future is wrapped in IO as its creation is side-effecting, and triggers eager computation).

    However, if you are fixed on using cats.effect.IO specifically you can simply use IO.fromFuture(IO(future)).

    You would have to use this (or some utility delegating to this) everywhere you need to translate Future into IO (or other F).