cats-effect icon indicating copy to clipboard operation
cats-effect copied to clipboard

The "Only Once" sample code in the Deferred documentation is outdated

Open floating-cat opened this issue 3 years ago • 0 comments

Page: https://typelevel.org/cats-effect/docs/std/deferred#only-once Parts:

Two processes will try to complete at the same time but only one will succeed, completing the deferred primitive exactly once. The loser one will raise an error when trying to complete a deferred already completed and automatically be canceled by the IO.race mechanism, that’s why we call attempt on the evaluation.

import cats.effect.{IO, Deferred}
import cats.syntax.all._

def start(d: Deferred[IO, Int]): IO[Unit] = {
  val attemptCompletion: Int => IO[Unit] = n => d.complete(n).attempt.void

  List(
    IO.race(attemptCompletion(1), attemptCompletion(2)),
    d.get.flatMap { n => IO(println(show"Result: $n")) }
  ).parSequence.void
}

val program: IO[Unit] =
  for {
    d <- Deferred[IO, Int]
    _ <- start(d)
  } yield ()

As far as I know, the latter one calls the complete and it would just return false wrapped in F and there is no error throws and it seems the code doesn't need to use the .attempt.void there too. Looks like this documentation is incorrect here. From my checking, the CE2's complete raise an error which is different in the CE3 now.

floating-cat avatar Jul 31 '22 11:07 floating-cat