首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >来自队列的fs2流不使用元素

来自队列的fs2流不使用元素
EN

Stack Overflow用户
提问于 2021-03-28 18:27:05
回答 1查看 54关注 0票数 1

我想从队列中创建流,它将把所有元素打印到控制台中。当前的代码片段没有打印任何内容:

代码语言:javascript
复制
object TestApp extends App {

  implicit val contextShift: ContextShift[IO] = IO.contextShift(ExecutionContext.global)

  private val value: IO[(fs2.Stream[IO, Unit], String => IO[Unit], () => IO[Unit])] = for {
    queue <- Queue.noneTerminated[IO, String]
  } yield {
    val stream: fs2.Stream[IO, Unit] = queue.dequeue.map(println)

    def send(msg: String): IO[Unit] = queue.enqueue1(Some(msg))

    def close(): IO[Unit] = queue.enqueue1(None)

    (stream, send _, close _)
  }

  val (stream, send, close) = value.unsafeRunSync()

  send("msg1").unsafeRunSync()
  send("msg2").unsafeRunSync()

}

创建流有什么问题?

EN

回答 1

Stack Overflow用户

发布于 2021-03-29 05:19:48

在您的示例中,您只是创建了一个队列并创建了流的描述。为了运行流,您需要调用compile,它将公开几个方法,允许运行和使用流的值,如toListfolddrain

在本例中,您对值并不真正感兴趣,因为您只想打印它们,所以应该使用drain

代码语言:javascript
复制
implicit val contextShift: ContextShift[IO] = IO.contextShift(ExecutionContext.global)
implicit val timer: Timer[IO] = IO.timer(ExecutionContext.global)

private val value: IO[(fs2.Stream[IO, Unit], String => IO[Unit], () => IO[Unit])] = for {
  queue <- Queue.noneTerminated[IO, String]
} yield {
  //I changed map to evalMap, since printing is effect and should be wrapped in IO
  val stream: fs2.Stream[IO, Unit] = queue.dequeue.evalMap(v => IO(println(v)))

  def send(msg: String): IO[Unit] = queue.enqueue1(Some(msg))

  def close(): IO[Unit] = queue.enqueue1(None)

  (stream, send _, close _)
}

val (stream, send, close) = value.unsafeRunSync()

send("msg1").unsafeRunSync()
send("msg2").unsafeRunSync()
//Closing of stream will be delayed by 5s and run in separate fiber
close().delayBy(5.seconds).start.unsafeRunSync()

//steam would block here until it's closed
stream.compile.drain.unsafeRunSync()
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66840439

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档