问题描述
考虑以下代码:
import cats.effect._
import cats.syntax.semigroupk._
import scala.concurrent.ExecutionContext
object TestFiber extends App {
implicit val contextShift: ContextShift[IO] =
IO.contextShift(ExecutionContext.global)
implicit val timer: Timer[IO] = IO.timer(ExecutionContext.global)
//prints before1
IO(println("before1")).attempt.start.flatMap(_.join).unsafeRunSync()
//prints before2
IO(println("before2")).attempt.start.flatMap(_.join).unsafeRunSync()
//prints what?
(
IO(println("before1")).attempt.start <+>
IO(println("before2")).attempt.start
).flatMap(_.join).unsafeRunSync()
}
正如预期的那样,第一和第二个示例分别打印before1
和before2
。
我对第三个示例的期望是,IO[Fiber[IO,Either[Throwable,Unit]]]
操作完成后,由SemigroupK
操作产生的光纤Fiber
就完成了,因此{{1} }和before1
应该已经打印。
不太可能
before2
仅打印(
IO(println("before1")).attempt.start <+>
IO(println("before2")).attempt.start
).flatMap(_.join).unsafeRunSync()
和
before1
仅打印(
IO(println("before2")).attempt.start <+>
IO(println("before1")).attempt.start
).flatMap(_.join).unsafeRunSync()
。
这是预期的行为吗? before2
都完成后,如何使Fiber
完成的正确方法是什么?
UPD:Fiber
个Traverse
中的一个List
是一个选项,但看起来很麻烦。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)