Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reimplement IO#guaranteeCase and IO.bracketFull #2126

Merged
merged 2 commits into from
Jul 14, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 10 additions & 13 deletions core/shared/src/main/scala/cats/effect/IO.scala
Original file line number Diff line number Diff line change
Expand Up @@ -400,7 +400,15 @@ sealed abstract class IO[+A] private () extends IOPlatform[A] {
* @see [[guarantee]] for the simpler version
*/
def guaranteeCase(finalizer: OutcomeIO[A @uncheckedVariance] => IO[Unit]): IO[A] =
IO.unit.bracketCase(_ => this)((_, oc) => finalizer(oc))
IO.uncancelable { poll =>
val finalized = poll(this).onCancel(finalizer(Outcome.canceled))
val handled = finalized.onError { e =>
finalizer(Outcome.errored(e)).handleErrorWith { t =>
IO.executionContext.flatMap(ec => IO(ec.reportFailure(t)))
}
}
handled.flatTap(a => finalizer(Outcome.succeeded(IO.pure(a))))
}

/**
* Handle any error, potentially recovering from it, by mapping it to another
Expand Down Expand Up @@ -1153,18 +1161,7 @@ object IO extends IOCompanionPlatform with IOLowPriorityImplicits {
def bracketFull[A, B](acquire: Poll[IO] => IO[A])(use: A => IO[B])(
release: (A, OutcomeIO[B]) => IO[Unit]): IO[B] =
IO.uncancelable { poll =>
acquire(poll).flatMap { a =>
def fin(oc: OutcomeIO[B]) = IO.uncancelable(_ => release(a, oc))

val finalized = poll(IO.defer(use(a))).onCancel(fin(Outcome.canceled))
val handled = finalized.onError { e =>
fin(Outcome.errored(e)) handleErrorWith { t =>
IO.executionContext.flatMap(ec => IO(ec.reportFailure(t)))
}
}

handled.flatTap(b => fin(Outcome.succeeded(IO.pure(b))))
}
acquire(poll).flatMap { a => IO.defer(poll(use(a))).guaranteeCase(release(a, _)) }
}

/*
Expand Down