Search code examples
scalaaws-lambdafs2

How do I use "writeOutputStream" with an fs2 Stream[IO, Byte]


I am trying to use fs2.io.writeOutputStream for the output to a Java AWS lambda fn. I don't know how to provide the implicit parameter it's looking for:

"no implicits found for parameter cs: ContextShift[IO]"

I found some documentation for creating my own implicit ContextShift object but that seems like overkill for what I'm trying to do.

final def handleRequest(in: InputStream, out: OutputStream, context: Context): Unit = (for {
  bytes <- in.compile.toList
  str   =  getString(bytes)
  args  <- decode(str).raiseIO
  _     <- produce(args).to(writeOutputStream(IO(out), global)).compile.drain
} yield Unit).unsafeRunAsyncAndForget() // throws exception in the case of Failure
// ------------------------------------------------
// produce(args: MyCaseClass): fs2.Stream[IO, Byte]

Solution

  • "By default, Cats Effect can provide instance of ContextShift[IO] that manages thread-pools, but only if there’s an ExecutionContext in scope or if IOApp is used."

    -- Cats-effect documentation.

    From an ExecutionContext.

    import cats.effect.{IO, ContextShift}
    import scala.concurrent.ExecutionContext.Implicits.global
    
    val contextShift = IO.contextShift(global)
    

    Using IOApp.

    import cats.effect.{IO, IOApp, ContextShift}
    
    object Main extends IOApp {
      override def run(args: List[String]): IO[ExitCode] = {
         val cs = implicitly[ContextShift[IO]]
      }
    }