Resource
Resource
is a data structure which encodes the idea of executingan 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.
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:
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))
}
}}}
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:
use:
{{{
def readFile(file: BufferedReader): IO[Content]
def readFile(file: BufferedReader): IO[Content]
open(file1).use(readFile)
}}}
}}}
Finalisation (in this case file closure) happens when the action
passed to
equivalent to:
passed to
use
terminates. Therefore, the code above is notequivalent to:
{{{
open(file1).use(IO.pure).flatMap(readFile)
}}}
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
so the following code opens and closes the resource twice:
use
is called,so the following code opens and closes the resource twice:
{{{
val file: Resource[IO, File]
file.use(read) >> file.use(read)
}}}
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
{{{
file.use { file => read(file) >> read(file) }
}}}
around, and call
use
once.{{{
file.use { file => read(file) >> read(file) }
}}}
The acquire and release actions passed to
interruptible, and release will run when the action passed to
succeeds, fails, or is interrupted. You can use makeCase
to specify a different release logic depending on each of the three
outcomes above.
make
are notinterruptible, 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.
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)
}
}
}}}
open(file1).use { in1 =>
open(file2).use { in2 =>
readFiles(in1, in2)
}
}
}}}
However, it is more idiomatic to compose multiple resources
together before
Nested resources are released in reverse order of acquisition.
Outer resources are released even if an inner use or release fails.
together before
use
, exploiting the fact that Resource
forms aMonad
, and therefore that resources can be nested throughflatMap
.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)
}
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")
outer <- mkResource("outer")
inner <- mkResource("inner")
} yield (outer, inner)
} yield (outer, inner)
r.use { case (a, b) =>
IO(println(s"Using $$a and $$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
}}}
{{{
Acquiring outer
Acquiring inner
Using outer and inner
Releasing inner
Releasing outer
}}}
A
finalisation through eval. Actions passed to
Resource
can also lift arbitrary actions that don't requirefinalisation through eval. Actions passed to
eval
preserve their interruptibility.Finally,
those instances as well as the other methods not covered here.
Resource
partakes in other abstractions such asMonadError
, Parallel
, and Monoid
, so make sure to explorethose instances as well as the other methods not covered here.
Resource
is encoded as a data structure, an ADT, described by thefollowing node types:
Normally users don't need to care about these node types, unless
conversions from
conversion from
case they can be interpreted through pattern matching.
conversions from
Resource
into something else is needed (e.g.conversion from
Resource
into a streaming data type), in whichcase they can be interpreted through pattern matching.
- Type Params
- A
-
the type of resource
- F
-
the effect type in which the resource is allocated and released
- Companion
- object
Value members
Methods
Allocates a resource and supplies it to the given function.
The resource is released as soon as the resulting
completed, whether normally or as a raised error.
The resource is released as soon as the resulting
F[B]
iscompleted, whether normally or as a raised error.
- Value Params
- f
-
the function to apply to the allocated resource
- Returns
-
the result of applying [F] to
Allocates a resource with a non-terminating use action.
Useful to run programs that are expressed entirely in
Useful to run programs that are expressed entirely in
Resource
.The finalisers run when the resulting program fails or gets interrupted.
Creates a FunctionK that, when applied, will allocate the resource and use it to run the given Kleisli.
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.
but within each of the two resources, nested finalizers are run in the usual
reverse order of acquisition.
Note that
that offers more convenient access to the same functionality as
Resource
also comes with a cats.Parallel
instancethat offers more convenient access to the same functionality as
both
, for example via parMapN
:{{{
def mkResource(name: String) = {
val acquire =
IO(scala.util.Random.nextInt(1000).millis).flatMap(IO.sleep) *>
IO(println(s"Acquiring $$name")).as(name)
def mkResource(name: String) = {
val acquire =
IO(scala.util.Random.nextInt(1000).millis).flatMap(IO.sleep) *>
IO(println(s"Acquiring $$name")).as(name)
val release = IO(println(s"Releasing $$name"))
Resource.make(acquire)(release)
}
Resource.make(acquire)(release)
}
val r = (mkResource("one"), mkResource("two"))
.parMapN((s1, s2) => s"I have $s1 and $s2")
.use(msg => IO(println(msg)))
}}}
.parMapN((s1, s2) => s"I have $s1 and $s2")
.use(msg => IO(println(msg)))
}}}
Races the evaluation of two resource allocations and returns the result of the winner,
except in the case of cancellation.
except in the case of cancellation.
Given a mapping function, transforms the resource provided by
this Resource.
this Resource.
This is the standard
Functor.map
. def mapK[G <: ([_$12] =>> Any)](f: FunctionK[F, G])(F: MonadCancel[F, ], G: MonadCancel[G, ]): Resource[G, A]
Given a natural transformation from
Resource from effect
The F and G constraint can also be satisfied by requiring a
MonadCancelThrow[F] and MonadCancelThrow[G] .
F
to G
, transforms thisResource from effect
F
to effect G
.The F and G constraint can also be satisfied by requiring a
MonadCancelThrow[F] and MonadCancelThrow[G] .
Runs
run even if resource acquisition fails or is canceled.
finalizer
when this resource is closed. Unlike the release action passed to Resource.make
, this willrun even if resource acquisition fails or is canceled.
Given a
as an action that runs all the finalizers for releasing it.
Resource
, possibly built by composing multipleResource
s monadically, returns the acquired resource, as wellas an action that runs all the finalizers for releasing it.
If the outer
that the finalizers will be called. However, if the outer
succeeds, it's up to the user to ensure the returned
is called once
F
fails or is interrupted, allocated
guaranteesthat the finalizers will be called. However, if the outer
F
succeeds, it's up to the user to ensure the returned
F[Unit]
is called once
A
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
program.
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
and
code that needs to modify or move the finalizer for an existing
resource.
expect separate acquire and release actions (like the
before
and
after
methods of many test frameworks), or complex librarycode that needs to modify or move the finalizer for an existing
resource.
Applies an effectful transformation to the allocated resource. Like a
flatMap
on F[A]
while maintaining the resource contextApplies an effectful transformation to the allocated resource. Like a
flatTap
on F[A]
while maintaining the resource contextAcquires the resource, runs
gb
and closes the resource once gb
terminates, fails or gets interrupted