Skip to content

Commit

Permalink
Best effort to improve deprecated attempt
Browse files Browse the repository at this point in the history
Fix F is `Sync`, We know that it has to be a `MonadCancelThrow`,
therefore We can use safer attempt and `unsafely` cast the result.
  • Loading branch information
lenguyenthanh committed Sep 7, 2024
1 parent cb1a293 commit 3b7d0ee
Showing 1 changed file with 23 additions and 19 deletions.
42 changes: 23 additions & 19 deletions kernel/shared/src/main/scala/cats/effect/kernel/Resource.scala
Original file line number Diff line number Diff line change
Expand Up @@ -701,27 +701,31 @@ sealed abstract class Resource[F[_], +A] extends Serializable {
}

@deprecated("Use overload with MonadCancelThrow", "3.6.0")
def attempt[E](F: ApplicativeError[F, E]): Resource[F, Either[E, A]] = {
implicit val x: ApplicativeError[F, E] = F
this match {
case Allocate(resource) =>
Resource.applyFull { poll =>
resource(poll).attempt.map {
case Left(error) => (Left(error), (_: ExitCase) => F.unit)
case Right((a, release)) => (Right(a), release)
}
}
case Bind(source, f) =>
Resource.unit.flatMap(_ => source.attempt(F)).flatMap {
case Left(error) => Resource.pure(error.asLeft)
case Right(s) => f(s).attempt(F)
def attempt[E](F: ApplicativeError[F, E]): Resource[F, Either[E, A]] =
F match {
case x: Sync[_] =>
attempt(x).asInstanceOf[Resource[F, Either[E, A]]]
case _ =>
implicit val x: ApplicativeError[F, E] = F
this match {
case Allocate(resource) =>
Resource.applyFull { poll =>
resource(poll).attempt.map {
case Left(error) => (Left(error), (_: ExitCase) => F.unit)
case Right((a, release)) => (Right(a), release)
}
}
case Bind(source, f) =>
Resource.unit.flatMap(_ => source.attempt(F)).flatMap {
case Left(error) => Resource.pure(error.asLeft)
case Right(s) => f(s).attempt(F)
}
case p @ Pure(_) =>
Resource.pure(p.a.asRight)
case e @ Eval(_) =>
Resource.eval(e.fa.attempt)
}
case p @ Pure(_) =>
Resource.pure(p.a.asRight)
case e @ Eval(_) =>
Resource.eval(e.fa.attempt)
}
}

def attempt(implicit F: MonadCancelThrow[F]): Resource[F, Either[Throwable, A]] =
Resource.applyFull[F, Either[Throwable, A]] { poll =>
Expand Down

0 comments on commit 3b7d0ee

Please sign in to comment.