首页 > 解决方案 > 如何将“writeOutputStream”与 fs2 Stream[IO, Byte] 一起使用

问题描述

我正在尝试使用fs2.io.writeOutputStream输出到 Java AWS lambda fn。我不知道如何提供它正在寻找的隐式参数:

“没有找到参数 cs 的隐含:ContextShift[IO]”

我找到了一些用于创建我自己的隐式 ContextShift 对象的文档,但这对于我正在尝试做的事情来说似乎有点过分了。

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]

标签: scalaaws-lambdafs2

解决方案


“默认情况下,Cats Effect 可以提供管理线程池的 ContextShift[IO] 实例,但前提是范围内有 ExecutionContext 或使用了 IOApp。”

- 猫效应文档

从一个ExecutionContext.

import cats.effect.{IO, ContextShift}
import scala.concurrent.ExecutionContext.Implicits.global

val contextShift = IO.contextShift(global)

使用IOApp.

import cats.effect.{IO, IOApp, ContextShift}

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

推荐阅读