sealed abstract class Resource[F[_], +A] extends Serializable
Resource
is a data structure which encodes the idea of executing an action which has an
associated finalizer that needs to be run when the action completes.
Examples include scarce resources like files, which need to be closed after use, or concurrent abstractions like locks, which need to be released after having been acquired.
There are several constructors to allocate a resource, the most common is make:
def open(file: File): Resource[IO, BufferedReader] = { val openFile = IO(new BufferedReader(new FileReader(file))) Resource.make(acquire = openFile)(release = f => IO(f.close)) }
and several methods to consume a resource, the most common is use:
def readFile(file: BufferedReader): IO[Content]
open(file1).use(readFile)
Finalisation (in this case file closure) happens when the action passed to use
terminates.
Therefore, the code above is _not_ equivalent to:
open(file1).use(IO.pure).flatMap(readFile)
which will instead result in an error, since the file gets closed after pure
, meaning that
.readFile
will then fail.
Also note that a _new_ resource is allocated every time use
is called, so the following
code opens and closes the resource twice:
val file: Resource[IO, File]
file.use(read) >> file.use(read)
If you want sharing, pass the result of allocating the resource around, and call use
once.
file.use { file => read(file) >> read(file) }
The acquire and release actions passed to make
are not interruptible, and release will run
when the action passed to use
succeeds, fails, or is interrupted. You can use
makeCase to specify a different release logic depending on each of the
three outcomes above.
It is also possible to specify an interruptible acquire though makeFull but be warned that this is an advanced concurrency operation, which requires some care.
Resource usage nests:
open(file1).use { in1 => open(file2).use { in2 => readFiles(in1, in2) } }
However, it is more idiomatic to compose multiple resources together before use
, exploiting
the fact that Resource
forms a Monad
, and therefore that resources can be nested through
flatMap
. Nested resources are released in reverse order of acquisition. Outer resources are
released even if an inner use or release fails.
def mkResource(s: String) = { val acquire = IO(println(s"Acquiring $$s")) *> IO.pure(s) def release(s: String) = IO(println(s"Releasing $$s")) Resource.make(acquire)(release) } val r = for { outer <- mkResource("outer") inner <- mkResource("inner") } yield (outer, inner) r.use { case (a, b) => IO(println(s"Using $$a and $$b")) }
On evaluation the above prints:
Acquiring outer Acquiring inner Using outer and inner Releasing inner Releasing outer
A Resource
can also lift arbitrary actions that don't require finalisation through
eval. Actions passed to eval
preserve their interruptibility.
Finally, Resource
partakes in other abstractions such as MonadError
, Parallel
, and
Monoid
, so make sure to explore those instances as well as the other methods not covered
here.
Resource
is encoded as a data structure, an ADT, described by the following node types:
Normally users don't need to care about these node types, unless conversions from Resource
into something else is needed (e.g. conversion from Resource
into a streaming data type),
in which case they can be interpreted through pattern matching.
- F
the effect type in which the resource is allocated and released
- A
the type of resource
- Source
- Resource.scala
- Alphabetic
- By Inheritance
- Resource
- Serializable
- AnyRef
- Any
- Hide All
- Show All
- Public
- Protected
Value Members
- final def !=(arg0: Any): Boolean
- Definition Classes
- AnyRef → Any
- def !>[B](that: Resource[F, B])(implicit F: MonadCancel[F, Throwable]): Resource[F, B]
- final def ##: Int
- Definition Classes
- AnyRef → Any
- final def ==(arg0: Any): Boolean
- Definition Classes
- AnyRef → Any
- def allocated[B >: A](implicit F: MonadCancel[F, Throwable]): F[(B, F[Unit])]
Given a
Resource
, possibly built by composing multipleResource
s monadically, returns the acquired resource, as well as an action that runs all the finalizers for releasing it.Given a
Resource
, possibly built by composing multipleResource
s monadically, returns the acquired resource, as well as an action that runs all the finalizers for releasing it.If the outer
F
fails or is interrupted,allocated
guarantees that the finalizers will be called. However, if the outerF
succeeds, it's up to the user to ensure the returnedF[Unit]
is called onceA
needs to be released. If the returnedF[Unit]
is not called, the finalizers will not be run.For this reason, this is an advanced and potentially unsafe api which can cause a resource leak if not used correctly, please prefer use as the standard way of running a
Resource
program.Use cases include interacting with side-effectful apis that expect separate acquire and release actions (like the
before
andafter
methods of many test frameworks), or complex library code that needs to modify or move the finalizer for an existing resource. - def allocatedCase[B >: A](implicit F: MonadCancel[F, Throwable]): F[(B, (ExitCase) => F[Unit])]
Given a
Resource
, possibly built by composing multipleResource
s monadically, returns the acquired resource, as well as a cleanup function that takes an exit case and runs all the finalizers for releasing it.Given a
Resource
, possibly built by composing multipleResource
s monadically, returns the acquired resource, as well as a cleanup function that takes an exit case and runs all the finalizers for releasing it.If the outer
F
fails or is interrupted,allocated
guarantees that the finalizers will be called. However, if the outerF
succeeds, it's up to the user to ensure the returnedExitCode => F[Unit]
is called onceA
needs to be released. If the returnedExitCode => F[Unit]
is not called, the finalizers will not be run.For this reason, this is an advanced and potentially unsafe api which can cause a resource leak if not used correctly, please prefer use as the standard way of running a
Resource
program.Use cases include interacting with side-effectful apis that expect separate acquire and release actions (like the
before
andafter
methods of many test frameworks), or complex library code that needs to modify or move the finalizer for an existing resource. - final def asInstanceOf[T0]: T0
- Definition Classes
- Any
- def attempt[E](implicit F: ApplicativeError[F, E]): Resource[F, Either[E, A]]
- def both[B](that: Resource[F, B])(implicit F: Concurrent[F]): Resource[F, (A, B)]
Allocates two resources concurrently, and combines their results in a tuple.
Allocates two resources concurrently, and combines their results in a tuple.
The finalizers for the two resources are also run concurrently with each other, but within _each_ of the two resources, nested finalizers are run in the usual reverse order of acquisition.
The same Resource.ExitCase is propagated to every finalizer. If both resources acquired successfully, the Resource.ExitCase is determined by the outcome of use. Otherwise, it is determined by which resource failed or canceled first during acquisition.
Note that
Resource
also comes with acats.Parallel
instance that offers more convenient access to the same functionality asboth
, for example viaparMapN
:import scala.concurrent.duration._ import cats.effect.{IO, Resource} import cats.effect.std.Random import cats.syntax.all._ def mkResource(name: String) = { val acquire = for { n <- Random.scalaUtilRandom[IO].flatMap(_.nextIntBounded(1000)) _ <- IO.sleep(n.millis) _ <- IO.println(s"Acquiring $$name") } yield name def release(name: String) = IO.println(s"Releasing $$name") Resource.make(acquire)(release) } val r = (mkResource("one"), mkResource("two")) .parMapN((s1, s2) => s"I have $s1 and $s2") .use(IO.println(_))
- def clone(): AnyRef
- Attributes
- protected[lang]
- Definition Classes
- AnyRef
- Annotations
- @throws(classOf[java.lang.CloneNotSupportedException]) @native()
- def combine[B >: A](that: Resource[F, B])(implicit A: Semigroup[B]): Resource[F, B]
- def combineK[B >: A](that: Resource[F, B])(implicit F: MonadCancel[F, Throwable], K: SemigroupK[F], G: Make[F]): Resource[F, B]
- final def eq(arg0: AnyRef): Boolean
- Definition Classes
- AnyRef
- def equals(arg0: AnyRef): Boolean
- Definition Classes
- AnyRef → Any
- def evalMap[B](f: (A) => F[B]): Resource[F, B]
Applies an effectful transformation to the allocated resource.
Applies an effectful transformation to the allocated resource. Like a
flatMap
onF[A]
while maintaining the resource context - def evalOn(ec: ExecutionContext)(implicit F: Async[F]): Resource[F, A]
- def evalTap[B](f: (A) => F[B]): Resource[F, A]
Applies an effectful transformation to the allocated resource.
Applies an effectful transformation to the allocated resource. Like a
flatTap
onF[A]
while maintaining the resource context - def finalize(): Unit
- Attributes
- protected[lang]
- Definition Classes
- AnyRef
- Annotations
- @throws(classOf[java.lang.Throwable])
- def flatMap[B](f: (A) => Resource[F, B]): Resource[F, B]
Implementation for the
flatMap
operation, as described via thecats.Monad
type class. - def forceR[B](that: Resource[F, B])(implicit F: MonadCancel[F, Throwable]): Resource[F, B]
- final def getClass(): Class[_ <: AnyRef]
- Definition Classes
- AnyRef → Any
- Annotations
- @native()
- def guaranteeCase(fin: (Outcome[[β$2$]Resource[F, β$2$], Throwable, A]) => Resource[F, Unit])(implicit F: MonadCancel[F, Throwable]): Resource[F, A]
- def handleErrorWith[B >: A, E](f: (E) => Resource[F, B])(implicit F: ApplicativeError[F, E]): Resource[F, B]
- def hashCode(): Int
- Definition Classes
- AnyRef → Any
- Annotations
- @native()
- final def isInstanceOf[T0]: Boolean
- Definition Classes
- Any
- def map[B](f: (A) => B): Resource[F, B]
Given a mapping function, transforms the resource provided by this Resource.
Given a mapping function, transforms the resource provided by this Resource.
This is the standard
Functor.map
. - def mapK[G[_]](f: ~>[F, G])(implicit F: MonadCancel[F, _], G: MonadCancel[G, _]): Resource[G, A]
Given a natural transformation from
F
toG
, transforms this Resource from effectF
to effectG
.Given a natural transformation from
F
toG
, transforms this Resource from effectF
to effectG
. The F and G constraint can also be satisfied by requiring a MonadCancelThrow[F] and MonadCancelThrow[G]. - final def ne(arg0: AnyRef): Boolean
- Definition Classes
- AnyRef
- final def notify(): Unit
- Definition Classes
- AnyRef
- Annotations
- @native()
- final def notifyAll(): Unit
- Definition Classes
- AnyRef
- Annotations
- @native()
- def onCancel(fin: Resource[F, Unit])(implicit F: MonadCancel[F, Throwable]): Resource[F, A]
- def onFinalize(finalizer: F[Unit])(implicit F: Applicative[F]): Resource[F, A]
Runs
finalizer
when this resource is closed.Runs
finalizer
when this resource is closed. Unlike the release action passed toResource.make
, this will run even if resource acquisition fails or is canceled. - def onFinalizeCase(f: (ExitCase) => F[Unit])(implicit F: Applicative[F]): Resource[F, A]
Like
onFinalize
, but the action performed depends on the exit case. - def preAllocate(precede: F[Unit]): Resource[F, A]
Runs
precede
before this resource is allocated. - def race[B](that: Resource[F, B])(implicit F: Concurrent[F]): Resource[F, Either[A, B]]
Races the evaluation of two resource allocations and returns the result of the winner, except in the case of cancelation.
- def start(implicit F: Concurrent[F]): Resource[F, Fiber[[β$3$]Resource[F, β$3$], Throwable, A]]
- def surround[B](gb: F[B])(implicit F: MonadCancel[F, Throwable]): F[B]
Acquires the resource, runs
gb
and closes the resource oncegb
terminates, fails or gets interrupted - def surroundK(implicit F: MonadCancel[F, Throwable]): ~>[F, F]
Creates a FunctionK that can run
gb
within a resource, which is then closed oncegb
terminates, fails or gets interrupted - final def synchronized[T0](arg0: => T0): T0
- Definition Classes
- AnyRef
- def toString(): String
- Definition Classes
- AnyRef → Any
- def use[B](f: (A) => F[B])(implicit F: MonadCancel[F, Throwable]): F[B]
Allocates a resource and supplies it to the given function.
Allocates a resource and supplies it to the given function. The resource is released as soon as the resulting
F[B]
is completed, whether normally or as a raised error.- f
the function to apply to the allocated resource
- returns
the result of applying [F] to
- def useEval[B](implicit ev: <:<[A, F[B]], F: MonadCancel[F, Throwable]): F[B]
For a resource that allocates an action (type
F[B]
), allocate that action, run it and release it. - def useForever(implicit F: Spawn[F]): F[Nothing]
Allocates a resource with a non-terminating use action.
Allocates a resource with a non-terminating use action. Useful to run programs that are expressed entirely in
Resource
.The finalisers run when the resulting program fails or gets interrupted.
- def useKleisli[B >: A, C](usage: Kleisli[F, B, C])(implicit F: MonadCancel[F, Throwable]): F[C]
Allocates the resource and uses it to run the given Kleisli.
- def useKleisliK[B >: A](implicit F: MonadCancel[F, Throwable]): ~>[[γ$0$]Kleisli[F, B, γ$0$], F]
Creates a FunctionK that, when applied, will allocate the resource and use it to run the given Kleisli.
- def use_(implicit F: MonadCancel[F, Throwable]): F[Unit]
Allocates a resource and closes it immediately.
- final def wait(): Unit
- Definition Classes
- AnyRef
- Annotations
- @throws(classOf[java.lang.InterruptedException])
- final def wait(arg0: Long, arg1: Int): Unit
- Definition Classes
- AnyRef
- Annotations
- @throws(classOf[java.lang.InterruptedException])
- final def wait(arg0: Long): Unit
- Definition Classes
- AnyRef
- Annotations
- @throws(classOf[java.lang.InterruptedException]) @native()