Skip to content

Commit

Permalink
Merge pull request #1368 from pkowalcze/resource-surround
Browse files Browse the repository at this point in the history
surround and surroundK added to Resource
  • Loading branch information
kubukoz authored Nov 6, 2020
2 parents eda37da + dda1b39 commit 1ff137f
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
19 changes: 19 additions & 0 deletions core/shared/src/test/scala/cats/effect/ResourceSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -469,6 +469,25 @@ class ResourceSpec extends BaseSpec with ScalaCheck with Discipline {
// }
// }

"surround - should wrap an effect in a usage and ignore the value produced by resource" in ticked {
implicit ticker =>
val r = Resource.liftF(IO.pure(0))
val surroundee = IO("hello")
val surrounded = r.surround(surroundee)

surrounded eqv surroundee
}

"surroundK - should wrap an effect in a usage, ignore the value produced by resource and return FunctionK" in ticked {
implicit ticker =>
val r = Resource.liftF(IO.pure(0))
val surroundee = IO("hello")
val surround = r.surroundK
val surrounded = surround(surroundee)

surrounded eqv surroundee
}

}

{
Expand Down
14 changes: 14 additions & 0 deletions kernel/shared/src/main/scala/cats/effect/kernel/Resource.scala
Original file line number Diff line number Diff line change
Expand Up @@ -417,6 +417,20 @@ sealed abstract class Resource[+F[_], +A] {
*/

private[effect] def invariant: Resource.InvariantResource[F0, A]

/**
* Acquires the resource, runs `gb` and closes the resource once `gb` terminates, fails or gets interrupted
*/
def surround[G[x] >: F[x]: Resource.Bracket, B](gb: G[B]): G[B] =
use(_ => gb)

/**
* Creates a FunctionK that can run `gb` within a resource, which is then closed once `gb` terminates, fails or gets interrupted
*/
def surroundK[G[x] >: F[x]: Resource.Bracket]: G ~> G =
new (G ~> G) {
override def apply[B](gb: G[B]): G[B] = surround(gb)
}
}

object Resource extends ResourceInstances with ResourcePlatform {
Expand Down

0 comments on commit 1ff137f

Please sign in to comment.