动态添加元素到fs2.Stream

发布于 2025-01-10 05:08:47 字数 104 浏览 5 评论 0原文

如何动态向 fs2.Stream 添加新元素?例如,我想将按下的按键作为流读取。我尝试使用 Stream.eval 以及内部使用foreverM 的函数来构建流,但事实证明这根本不是一个好主意。

How may I add new elements to fs2.Stream dynamically? For example, I would like to read key pressed as stream. I have tried to build the stream using Stream.eval with a function that use foreverM inside, but it turned out to not be a great idea at all.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

木緿 2025-01-17 05:08:47

一般来说,您不能将任何内容推送到 fs2.Stream。流是惰性的、基于拉动的结构,这意味着流按需请求下一个元素。

在这种特定情况下,您可以通过生成一个流来处理该问题,该流表示“当需要另一个元素时,读取控制台输入”。

import cats.effect.std.Console
def readNext: IO[String] = Console[IO].readLine // Or however else
val inputs = fs2.Stream.repeatEval(readNext)

当元素实际上必须是推送时,更通用的解决方案是推送元素使用 队列,然后 从队列创建流


第三种选择是使用 fs2-io 的 内置对控制台的支持

fs2.io.stdinUtf8[F](bufferSize): Stream[F, String]

In general, you can't push anything to an fs2.Stream. Streams are lazy, pull-based structures, meaning that the stream asks for next elements on demand.

In this specific case, you can handle that by producing a stream that says "when another element is needed, read console input",

import cats.effect.std.Console
def readNext: IO[String] = Console[IO].readLine // Or however else
val inputs = fs2.Stream.repeatEval(readNext)

A more generic solution to pushing elements when it has to actually be a push is to use a Queue, and then create a Stream from the Queue


A third option is to use fs2-io's built in support for the console,

fs2.io.stdinUtf8[F](bufferSize): Stream[F, String]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文