Mun*_* Ar 2 queue scala stream fs2
我是一个新手,试图掌握 fs2 队列背后的直觉。我正在尝试做一个从Stream[IO, Int]. 但是文档对我来说是不够的,因为它直接深入到高级内容中。
这是我到目前为止所做的:
import cats.effect.{ ExitCode, IO, IOApp}
import fs2._
import fs2.concurrent.Queue
class QueueInt(q: Queue[IO, Int]) {
def startPushingtoQueue: Stream[IO, Unit] = {
Stream(1, 2, 3).covary[IO].through(q.enqueue)
q.dequeue.evalMap(n => IO.delay(println(s"Pulling element $n from Queue")))
}
}
object testingQueues extends IOApp {
override def run(args: List[String]): IO[ExitCode] = {
val stream = for {
q <- Queue.bounded(10)
b = new QueueInt(q)
_ <- b.startPushingtoQueue.drain
} yield ()
}
}
Run Code Online (Sandbox Code Playgroud)
问题 1:我No implicit argument of type Concurrent[F_],
知道我没有使用任何并发效果我似乎无法弄清楚我错过了什么?
问题 2:如何打印结果。
问题 3:有人可以指导我学习 fs2 的一些资源吗
我在您的代码中发现了几个问题:
q <- Queue.bounded[IO, Unit](10) // it will fix your error with implicits
Run Code Online (Sandbox Code Playgroud)
IO[Unit],但为了让它运行你必须从run方法中返回它。您还需要将类型从 unit 更改为ExitCode:stream.as(ExitCode.Success)
Run Code Online (Sandbox Code Playgroud)
startPushingToQueue您正在创建,Steam但没有在任何地方分配它。它只会创建流的描述,但不会运行。我认为您想要实现的是创建一个将元素推送到队列的方法,以及另一个从队列中获取元素并打印它们的方法。请检查我的解决方案:
import cats.effect.{ ExitCode, IO, IOApp}
import fs2._
import fs2.concurrent.Queue
import scala.concurrent.duration._
class QueueInt(q: Queue[IO, Int])(implicit timer: Timer[IO]) { //I need implicit timer for metered
def startPushingToQueue: Stream[IO, Unit] = Stream(1, 2, 3)
.covary[IO]
.evalTap(n => IO.delay(println(s"Pushing element $n to Queue"))) //eval tap evaluates effect on an element but doesn't change stream
.metered(500.millis) //it will create 0.5 delay between enqueueing elements of stream,
// I added it to make visible that elements can be pushed and pulled from queue concurrently
.through(q.enqueue)
def pullAndPrintElements: Stream[IO, Unit] = q.dequeue.evalMap(n => IO.delay(println(s"Pulling element $n from Queue")))
}
object testingQueues extends IOApp {
override def run(args: List[String]): IO[ExitCode] = {
val program = for {
q <- Queue.bounded[IO, Int](10)
b = new QueueInt(q)
_ <- b.startPushingToQueue.compile.drain.start //start at the end will start running stream in another Fiber
_ <- b.pullAndPrintElements.compile.drain //compile.draing compiles stream into io byt pulling all elements.
} yield ()
program.as(ExitCode.Success)
}
}
Run Code Online (Sandbox Code Playgroud)
在控制台上,您将看到有关从交错队列中推和拉的行。如果您删除,start您将看到startPushingToQueue在推送所有元素后首先从完成中流出,然后才pullAndPrintElements开始。
如果您正在寻找学习 fs2 的好资源,我建议您应该从查看与 fs2 相关的演讲开始。比起旧的,更喜欢新的谈话,因为他们可以引用旧的 API。
您还应该查看有关 fs2 文档的指南。
| 归档时间: |
|
| 查看次数: |
661 次 |
| 最近记录: |