Always
Constructs a lazy Coeval instance.
This type can be used for "lazy" values. In some sense it is equivalent to using a Function0 value.
Value members
Concrete methods
Inherited methods
Runs this coeval first and then, when successful, the given coeval. Returns the result of the given coeval.
Runs this coeval first and then, when successful, the given coeval. Returns the result of the given coeval.
Example:
val combined = Coeval{println("first"); "first"} *> Coeval{println("second"); "second"}
// Prints "first" and then "second"
// Result value will be "second"
- Inherited from:
- Coeval
Runs this coeval first and then, when successful, the given coeval. Returns the result of this coeval.
Runs this coeval first and then, when successful, the given coeval. Returns the result of this coeval.
Example:
val combined = Coeval{println("first"); "first"} <* Coeval{println("second"); "second"}
// Prints "first" and then "second"
// Result value will be "first"
- Inherited from:
- Coeval
Runs this underlying computation first and then, when successful, the given one. Returns the result of the given underlying computation.
Runs this underlying computation first and then, when successful, the given one. Returns the result of the given underlying computation.
Example:
val combined = Coeval{println("first"); "first"} >> Coeval{println("second"); "second"}
// Prints "first" and then "second"
// Result value will be "second"
- Inherited from:
- Coeval
Returns this coeval mapped to the supplied value.
Returns this coeval mapped to the supplied value.
- Inherited from:
- Coeval
Creates a new Coeval that will expose any triggered error from the source.
Creates a new Coeval that will expose any triggered error from the source.
val fa: Coeval[Int] =
Coeval.raiseError[Int](new RuntimeException("dummy"))
val fe: Coeval[Either[Throwable, Int]] =
fa.attempt
fe.map {
case Left(_) => Int.MaxValue
case Right(v) => v
}
By exposing errors by lifting the Coeval
's result into an
Either
value, we can handle those errors in flatMap
transformations.
Also see materialize for working with Scala's Try or redeemWith for an alternative.
- Inherited from:
- Coeval
Returns a task that treats the source as the acquisition of a resource,
which is then exploited by the use
function and then released
.
Returns a task that treats the source as the acquisition of a resource,
which is then exploited by the use
function and then released
.
The bracket
operation is the equivalent of the
try {} finally {}
statements from mainstream languages, installing
the necessary exception handler to release the resource in the event of
an exception being raised during the computation. If an exception is raised,
then bracket
will re-raise the exception ''after'' performing the release
.
Example:
import java.io._
def readFile(file: File): Coeval[String] = {
// Opening a file handle for reading text
val acquire = Coeval.eval(new BufferedReader(
new InputStreamReader(new FileInputStream(file), "utf-8")
))
acquire.bracket { in =>
// Usage part
Coeval.eval {
// Yes, ugly Java, non-FP loop;
// side-effects are suspended though
var line: String = ""
val buff = new StringBuilder()
while (line != null) {
line = in.readLine()
if (line != null) buff.append(line)
}
buff.toString()
}
} { in =>
// The release part
Coeval.eval(in.close())
}
}
'''NOTE on error handling''': one big
difference versus try {} finally {}
is that, in case
both the release
function and the use
function throws,
the error raised by use
gets signaled and the error
raised by release
gets reported with System.err
for
Coeval or with
Scheduler.reportFailure
for Task.
For example:
Coeval("resource").bracket { _ =>
// use
Coeval.raiseError(new RuntimeException("Foo"))
} { _ =>
// release
Coeval.raiseError(new RuntimeException("Bar"))
}
In this case the error signaled downstream is `"Foo"`,
while the `"Bar"` error gets reported. This is consistent
with the behavior of Haskell's `bracket` operation and NOT
with `try {} finally {}` from Scala, Java or JavaScript.
- Value parameters:
- release
is a function that gets called after
use
terminates, either normally or in error, receiving as input the resource that needs to be released- use
is a function that evaluates the resource yielded by the source, yielding a result that will get generated by the task returned by this
bracket
function
- See also:
bracketCase and bracketE
- Inherited from:
- Coeval
Returns a new task that treats the source task as the
acquisition of a resource, which is then exploited by the use
function and then released
, with the possibility of
distinguishing between successful completion and failure, such
that an appropriate release of resources can be executed.
Returns a new task that treats the source task as the
acquisition of a resource, which is then exploited by the use
function and then released
, with the possibility of
distinguishing between successful completion and failure, such
that an appropriate release of resources can be executed.
The bracketCase
operation is the equivalent of
try {} catch {} finally {}
statements from mainstream languages
when used for the acquisition and release of resources.
The bracketCase
operation installs the necessary exception handler
to release the resource in the event of an exception being raised
during the computation.
In comparison with the simpler bracket version, this one
allows the caller to differentiate between normal termination and
termination in error via an ExitCase
parameter.
- Value parameters:
- release
is a function that gets called after
use
terminates, either normally or in error, receiving as input the resource that needs that needs release, along with the result ofuse
- use
is a function that evaluates the resource yielded by the source, yielding a result that will get generated by this function on evaluation
- See also:
- Inherited from:
- Coeval
Returns a task that treats the source task as the acquisition of a resource,
which is then exploited by the use
function and then released
, with
the possibility of distinguishing between successful termination and
error, such that an appropriate release of resources can be executed.
Returns a task that treats the source task as the acquisition of a resource,
which is then exploited by the use
function and then released
, with
the possibility of distinguishing between successful termination and
error, such that an appropriate release of resources can be executed.
The bracket
operation is the equivalent of the
try {} finally {}
statements from mainstream languages, installing
the necessary exception handler to release the resource in the event of
an exception being raised during the computation. If an exception is raised,
then bracket
will re-raise the exception ''after'' performing the release
.
The release
function receives as input:
Left(error)
in caseuse
terminated with an errorRight(b)
in case of success
'''NOTE on error handling''': one big
difference versus try {} finally {}
is that, in case
both the release
function and the use
function throws,
the error raised by use
gets signaled and the error
raised by release
gets reported with System.err
for
Coeval or with
Scheduler.reportFailure
for Task.
For example:
Coeval("resource").bracket { _ =>
// use
Coeval.raiseError(new RuntimeException("Foo"))
} { _ =>
// release
Coeval.raiseError(new RuntimeException("Bar"))
}
In this case the error signaled downstream is `"Foo"`,
while the `"Bar"` error gets reported. This is consistent
with the behavior of Haskell's `bracket` operation and NOT
with `try {} finally {}` from Scala, Java or JavaScript.
- Value parameters:
- release
is a function that gets called after
use
terminates, either normally or in error, receiving as input the resource that needs that needs release, along with the result ofuse
- use
is a function that evaluates the resource yielded by the source, yielding a result that will get generated by this function on evaluation
- See also:
bracket and bracketCase
- Inherited from:
- Coeval
Dematerializes the source's result from a Try
.
Dematerializes the source's result from a Try
.
This equivalence always holds:
fa.materialize.dematerialize <-> fa
- Inherited from:
- Coeval
Returns a new Coeval
in which f
is scheduled to be run on completion.
This would typically be used to release any resources acquired by this
Coeval
.
Returns a new Coeval
in which f
is scheduled to be run on completion.
This would typically be used to release any resources acquired by this
Coeval
.
- Inherited from:
- Coeval
Returns a failed projection of this coeval.
Returns a failed projection of this coeval.
The failed projection is a Coeval
holding a value of type Throwable
,
emitting the error yielded by the source, in case the source fails,
otherwise if the source succeeds the result will fail with a
NoSuchElementException
.
- Inherited from:
- Coeval
Creates a new Coeval
by applying a function to the successful result
of the source, and returns a new instance equivalent
to the result of the function.
Creates a new Coeval
by applying a function to the successful result
of the source, and returns a new instance equivalent
to the result of the function.
The application of flatMap
is always lazy and because of the
implementation it is memory safe and thus it can be used in
recursive loops.
Sample:
import scala.util.Random
def randomEven: Coeval[Int] =
Coeval(Random.nextInt()).flatMap { x =>
if (x < 0 || x % 2 == 1)
randomEven // retry
else
Coeval.now(x)
}
- Inherited from:
- Coeval
Describes flatMap-driven loops, as an alternative to recursive functions.
Describes flatMap-driven loops, as an alternative to recursive functions.
Sample:
import scala.util.Random
val random = Coeval(Random.nextInt())
val loop = random.flatMapLoop(Vector.empty[Int]) { (a, list, continue) =>
val newList = list :+ a
if (newList.length < 5)
continue(newList)
else
Coeval.now(newList)
}
Given a source Coeval that emits another Coeval, this function flattens the result, returning a Coeval equivalent to the emitted Coeval by the source.
Triggers the evaluation of the source, executing the given function for the generated element.
Triggers the evaluation of the source, executing the given function for the generated element.
The application of this function has strict behavior, as the coeval is immediately executed.
- Inherited from:
- Coeval
Returns a new task that upon evaluation will execute
the given function for the generated element,
transforming the source into a Coeval[Unit]
.
Executes the given finalizer
when the source is finished,
either in success or in error, or if canceled.
Executes the given finalizer
when the source is finished,
either in success or in error, or if canceled.
This variant of guaranteeCase evaluates the given finalizer
regardless of how the source gets terminated:
- normal completion
- completion in error
- cancellation
As best practice, it's not a good idea to release resources
via guaranteeCase
in polymorphic code. Prefer bracket
for the acquisition and release of resources.
- See also:
guaranteeCase for the version that can discriminate between termination conditions
bracket for the more general operation
- Inherited from:
- Coeval
Executes the given finalizer
when the source is finished,
either in success or in error, or if canceled, allowing
for differentiating between exit conditions.
Executes the given finalizer
when the source is finished,
either in success or in error, or if canceled, allowing
for differentiating between exit conditions.
This variant of guarantee injects an ExitCase in the provided function, allowing one to make a difference between:
- normal completion
- completion in error
- cancellation
As best practice, it's not a good idea to release resources
via guaranteeCase
in polymorphic code. Prefer bracketCase
for the acquisition and release of resources.
- See also:
guarantee for the simpler version
bracketCase for the more general operation
- Inherited from:
- Coeval
Creates a new Coeval that will expose any triggered error from the source.
Creates a new Coeval that will expose any triggered error from the source.
Also see attempt for working with Scala's Either or redeemWith for an alternative.
- Inherited from:
- Coeval
Memoizes (caches) the result of the source and reuses it on
subsequent invocations of value
.
Memoizes (caches) the result of the source and reuses it on
subsequent invocations of value
.
The resulting coeval will be idempotent, meaning that evaluating the resulting coeval multiple times will have the same effect as evaluating it once.
'''UNSAFE''' — this operation allocates a shared, mutable reference, which can break in certain cases referential transparency, even if this operation guarantees idempotency (i.e. referential transparency implies idempotency, but idempotency does not imply referential transparency).
The allocation of a mutable reference is known to be a
side effect, thus breaking referential transparency,
even if calling this method does not trigger the evaluation
of side effects suspended by the source.
Use with care. Sometimes it's easier to just keep a shared,
memoized reference to some connection, but keep in mind
it might be better to pass such a reference around as
a parameter.
- See also:
memoizeOnSuccess for a version that only caches successful results
- Inherited from:
- Coeval
Memoizes (cache) the successful result of the source
and reuses it on subsequent invocations of value
.
Thrown exceptions are not cached.
Memoizes (cache) the successful result of the source
and reuses it on subsequent invocations of value
.
Thrown exceptions are not cached.
The resulting coeval will be idempotent, but only if the result is successful.
'''UNSAFE''' — this operation allocates a shared, mutable reference, which can break in certain cases referential transparency, even if this operation guarantees idempotency (i.e. referential transparency implies idempotency, but idempotency does not imply referential transparency).
The allocation of a mutable reference is known to be a
side effect, thus breaking referential transparency,
even if calling this method does not trigger the evaluation
of side effects suspended by the source.
Use with care. Sometimes it's easier to just keep a shared,
memoized reference to some connection, but keep in mind
it might be better to pass such a reference around as
a parameter.
Creates a new coeval that in case of error will fallback to the given backup coeval.
Creates a new coeval that in case of error will fallback to the given backup coeval.
- Inherited from:
- Coeval
Creates a new coeval that will handle any matching throwable that this coeval might emit.
Creates a new coeval that will handle any matching throwable that this coeval might emit.
See onErrorRecover for the version that takes a partial function.
- Inherited from:
- Coeval
Creates a new coeval that will handle any matching throwable that this coeval might emit by executing another coeval.
Creates a new coeval that will handle any matching throwable that this coeval might emit by executing another coeval.
See onErrorRecoverWith for the version that takes a partial function.
- Inherited from:
- Coeval
Creates a new coeval that on error will try to map the error to another value using the provided partial function.
Creates a new coeval that on error will try to map the error to another value using the provided partial function.
See onErrorHandle for the version that takes a total function.
- Inherited from:
- Coeval
Creates a new coeval that will try recovering from an error by matching it with another coeval using the given partial function.
Creates a new coeval that will try recovering from an error by matching it with another coeval using the given partial function.
See onErrorHandleWith for the version that takes a total function.
- Inherited from:
- Coeval
Creates a new coeval that in case of error will retry executing the source again and again, until it succeeds.
Creates a new coeval that in case of error will retry executing the source again and again, until it succeeds.
In case of continuous failure the total number of executions
will be maxRetries + 1
.
- Inherited from:
- Coeval
Creates a new coeval that in case of error will retry executing the source again and again, until it succeeds.
Creates a new coeval that in case of error will retry executing the source again and again, until it succeeds.
In case of continuous failure the total number of executions
will be maxRetries + 1
.
- Inherited from:
- Coeval
On error restarts the source with a customizable restart loop.
On error restarts the source with a customizable restart loop.
This operation keeps an internal state
, with a start value, an internal
state that gets evolved and based on which the next step gets decided,
e.g. should it restart, or should it give up and rethrow the current error.
Example that implements a simple retry policy that retries for a maximum of 10 times before giving up:
import scala.util.Random
val fa = Coeval {
if (Random.nextInt(20) > 10)
throw new RuntimeException("boo")
else 78
}
fa.onErrorRestartLoop(10) { (err, maxRetries, retry) =>
if (maxRetries > 0)
// Do next retry please
retry(maxRetries - 1)
else
// No retries left, rethrow the error
Coeval.raiseError(err)
}
The given function injects the following parameters:
error
reference that was thrown- the current
state
, based on which a decision for the retry is made retry: S => Task[B]
function that schedules the next retry
- Value parameters:
- f
is a function that injects the current error, state, a function that can signal a retry is to be made and returns the next coeval
- initial
is the initial state used to determine the next on error retry cycle
- Inherited from:
- Coeval
Returns a new value that transforms the result of the source,
given the recover
or map
functions, which get executed depending
on whether the result is successful or if it ends in error.
Returns a new value that transforms the result of the source,
given the recover
or map
functions, which get executed depending
on whether the result is successful or if it ends in error.
This is an optimization on usage of attempt and map, this equivalence being true:
coeval.redeem(recover, map) <-> coeval.attempt.map(_.fold(recover, map))
Usage of redeem
subsumes onErrorHandle because:
coeval.redeem(fe, id) <-> coeval.onErrorHandle(fe)
- Value parameters:
- map
is a function used for mapping the result of the source in case it ends in success
- recover
is a function used for error recover in case the source ends in error
- Inherited from:
- Coeval
Returns a new value that transforms the result of the source,
given the recover
or bind
functions, which get executed depending
on whether the result is successful or if it ends in error.
Returns a new value that transforms the result of the source,
given the recover
or bind
functions, which get executed depending
on whether the result is successful or if it ends in error.
This is an optimization on usage of attempt and flatMap, this equivalence being available:
coeval.redeemWith(recover, bind) <-> coeval.attempt.flatMap(_.fold(recover, bind))
Usage of redeemWith
subsumes onErrorHandleWith because:
coeval.redeemWith(fe, F.pure) <-> coeval.onErrorHandleWith(fe)
Usage of redeemWith
also subsumes flatMap because:
coeval.redeemWith(Coeval.raiseError, fs) <-> coeval.flatMap(fs)
- Value parameters:
- bind
is the function that gets to transform the source in case of success
- recover
is the function that gets called to recover the source in case of error
- Inherited from:
- Coeval
Given a predicate function, keep retrying the coeval until the function returns true.
Given a predicate function, keep retrying the coeval until the function returns true.
- Inherited from:
- Coeval
Creates a new Coeval
that will run the given function in case of error
and raise the original error in case the provided function is successful.
Creates a new Coeval
that will run the given function in case of error
and raise the original error in case the provided function is successful.
Example:
// will result in Left("Error")
Coeval
.raiseError(new RuntimeException("Error"))
.tapError(err => Coeval(err))
If provided function returns an error then the resulting coeval will raise that error instead.
Example:
// will result in Left("Error2")
Coeval
.raiseError(new RuntimeException("Error1"))
.tapError(err => Coeval.raiseError(new RuntimeException("Error2")))
- Inherited from:
- Coeval
Creates a new Coeval
that will run the given function on the success
and return the original value.
Creates a new Coeval
that will run the given function on the success
and return the original value.
- Inherited from:
- Coeval
Converts the source Coeval into any F[_]
that implements
cats.effect.Sync
.
Converts the source Coeval into any F[_]
that implements
cats.effect.Sync
.
For example it can work with cats.effect.IO
:
import cats._
import cats.effect._
val source = Coeval { 1 + 1 }
val asIO: IO[Int] = source.to[IO]
val asEval: Eval[Int] = source.to[Eval]
val asTask: Task[Int] = source.to[Task]
- Inherited from:
- Coeval
Converts the source to any value that implements cats.effect.Sync
.
Converts the source to any value that implements cats.effect.Sync
.
Prefer to use to, this method is provided in order to force
the usage of cats.effect.Sync
instances (instead of CoevalLift).
- Inherited from:
- Coeval
Evaluates the underlying computation and returns the result.
Evaluates the underlying computation and returns the result.
NOTE: this can throw exceptions.
Alias for apply.
'''UNSAFE''' — this operation can trigger the execution of side effects, which break referential transparency and is thus not a pure function.
In FP code use with care, suspended in another `Coeval`
or [[monix.eval.Task Task]], or at the edge of the FP
program.
- Inherited from:
- Coeval
Zips the values of this
and that
coeval, and creates a new coeval
that will emit the tuple of their results.
Zips the values of this
and that
coeval, and creates a new coeval
that will emit the tuple of their results.
- Inherited from:
- Coeval
Deprecated and Inherited methods
Deprecated — use redeem instead.
Deprecated — use redeem instead.
Coeval.redeem is the same operation, but with a different name and the
function parameters in an inverted order, to make it consistent with fold
on Either
and others (i.e. the function for error recovery is at the left).
- Deprecated
[Since version 3.0.0-RC2]
- Inherited from:
- Coeval
Deprecated — use redeemWith instead.
Deprecated — use redeemWith instead.
Coeval.redeemWith is the same operation, but with a different name and the
function parameters in an inverted order, to make it consistent with fold
on Either
and others (i.e. the function for error recovery is at the left).
- Deprecated
[Since version 3.0.0-RC2]
- Inherited from:
- Coeval