sealed abstract class Coeval[+A] extends () => A with Serializable
Coeval
represents lazy computations that can execute synchronously.
Word definition and origin:
- Having the same age or date of origin; a contemporary; synchronous.
- From the Latin "coævus": com- ("equal") in combination with aevum (aevum, "age").
- The constructor of
Coeval
is the dual of an expression that evaluates to anA
.
There are three evaluation strategies:
- now or raiseError: for describing strict values, evaluated immediately
- evalOnce: expressions evaluated a single time
- eval: expressions evaluated every time the value is needed
The Once
and Always
are both lazy strategies while
Now
and Error
are eager. Once
and Always
are
distinguished from each other only by memoization: once evaluated
Once
will save the value to be returned immediately if it is
needed again. Always
will run its computation every time.
Both Now
and Error
are represented by the
Eager trait, a sub-type of Coeval
that can be used as a replacement for Scala's own Try
type.
Coeval
supports stack-safe lazy computation via the
.map and .flatMap methods,
which use an internal trampoline to avoid stack overflows.
Computations done within .map
and .flatMap
are always
lazy, even when applied to a
Coeval.Eager instance (e.g.
Coeval.Now,
Coeval.Error).
Evaluation Strategies
The "now" and "raiseError" builders are building Coeval
instances out of strict values:
val fa = Coeval.now(1) fa.value() // => 1 val fe = Coeval.raiseError(new RuntimeException("dummy")) fe.failed // => has RuntimeException
The "always" strategy is equivalent with a plain function:
// For didactic purposes, don't use shared vars at home :-) var i = 0 val coeval = Coeval.eval { i += 1; i } coeval.value() // => 1 coeval.value() // => 2 coeval.value() // => 3
The "once" strategy is equivalent with Scala's lazy val
(along with thread-safe idempotency guarantees):
var j = 0 val coevalOnce = Coeval.evalOnce { j += 1; j } coevalOnce.value() // => 1 coevalOnce.value() // => 1 coevalOnce.value() // => 1
Versus Task
The other option of suspending side-effects is Task. As a quick comparison:
Coeval
's execution is always immediate / synchronous, whereasTask
can describe asynchronous computationsCoeval
is not cancelable, obviously, since execution is immediate and there's nothing to cancel
Versus cats.Eval
The Coeval
data type is very similar with cats.Eval.
As a quick comparison:
cats.Eval
is only for controlling laziness, but it doesn't handle side effects, hencecats.Eval
is aComonad
- Monix's
Coeval
can handle side effects as well and thus it implementsMonadError[Coeval, Throwable]
andcats.effect.Sync
, providing error-handling utilities
If you just want to delay the evaluation of a pure expression
use cats.Eval
, but if you need to suspend side effects or you
need error handling capabilities, then use Coeval
.
- Self Type
- Coeval[A]
- Source
- Coeval.scala
- Alphabetic
- By Inheritance
- Coeval
- Serializable
- Function0
- AnyRef
- Any
- Hide All
- Show All
- Public
- Protected
Value Members
- final def !=(arg0: Any): Boolean
- Definition Classes
- AnyRef → Any
- final def ##(): Int
- Definition Classes
- AnyRef → Any
- final def *>[B](that: Coeval[B]): Coeval[B]
Runs this coeval first and then, when successful, 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"
- Annotations
- @inline()
- final def <*[B](that: Coeval[B]): Coeval[A]
Runs this coeval first and then, when successful, the given 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"
- Annotations
- @inline()
- final def ==(arg0: Any): Boolean
- Definition Classes
- AnyRef → Any
- final def >>[B](that: => Coeval[B]): Coeval[B]
Runs this underlying computation first and then, when successful, the given one.
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"
- def apply(): A
Evaluates the underlying computation and returns the result.
Evaluates the underlying computation and returns the result.
NOTE: this can throw exceptions.
// For didactic purposes, don't do shared vars at home :-) var i = 0 val fa = Coeval { i += 1; i } fa() // => 1 fa() // => 2 fa() // => 3
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 Task, or at the edge of the FP program.- Definition Classes
- Coeval → Function0
- Annotations
- @UnsafeBecauseImpure()
- final def asInstanceOf[T0]: T0
- Definition Classes
- Any
- final def attempt: Coeval[Either[Throwable, A]]
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 anEither
value, we can handle those errors inflatMap
transformations.Also see materialize for working with Scala's Try or redeemWith for an alternative.
- final def bracket[B](use: (A) => Coeval[B])(release: (A) => Coeval[Unit]): Coeval[B]
Returns a task that treats the source as the acquisition of a resource, which is then exploited by the
use
function and thenreleased
.Returns a task that treats the source as the acquisition of a resource, which is then exploited by the
use
function and thenreleased
.The
bracket
operation is the equivalent of thetry {} 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, thenbracket
will re-raise the exception after performing therelease
.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 = null val buff = new StringBuilder() do { line = in.readLine() if (line != null) buff.append(line) } while (line != null) 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 therelease
function and theuse
function throws, the error raised byuse
gets signaled and the error raised byrelease
gets reported withSystem.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'sbracket
operation and NOT withtry {} finally {}
from Scala, Java or JavaScript.- 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- 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
- See also
bracketCase and bracketE
- final def bracketCase[B](use: (A) => Coeval[B])(release: (A, ExitCase[Throwable]) => Coeval[Unit]): Coeval[B]
Returns a new task that treats the source task as the acquisition of a resource, which is then exploited by the
use
function and thenreleased
, 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 thenreleased
, 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 oftry {} 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.- use
is a function that evaluates the resource yielded by the source, yielding a result that will get generated by this function on evaluation
- 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
- final def bracketE[B](use: (A) => Coeval[B])(release: (A, Either[Throwable, B]) => Coeval[Unit]): Coeval[B]
Returns a task that treats the source task as the acquisition of a resource, which is then exploited by the
use
function and thenreleased
, 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 thenreleased
, 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 thetry {} 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, thenbracket
will re-raise the exception after performing therelease
.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 therelease
function and theuse
function throws, the error raised byuse
gets signaled and the error raised byrelease
gets reported withSystem.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'sbracket
operation and NOT withtry {} finally {}
from Scala, Java or JavaScript.- use
is a function that evaluates the resource yielded by the source, yielding a result that will get generated by this function on evaluation
- 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
- See also
bracket and bracketCase
- def clone(): AnyRef
- Attributes
- protected[lang]
- Definition Classes
- AnyRef
- Annotations
- @throws(classOf[java.lang.CloneNotSupportedException]) @native() @HotSpotIntrinsicCandidate()
- final def dematerialize[B](implicit ev: <:<[A, Try[B]]): Coeval[B]
Dematerializes the source's result from a
Try
.Dematerializes the source's result from a
Try
.This equivalence always holds:
fa.materialize.dematerialize <-> fa
- final def doOnFinish(f: (Option[Throwable]) => Coeval[Unit]): Coeval[A]
Returns a new
Coeval
in whichf
is scheduled to be run on completion.Returns a new
Coeval
in whichf
is scheduled to be run on completion. This would typically be used to release any resources acquired by thisCoeval
. - final def eq(arg0: AnyRef): Boolean
- Definition Classes
- AnyRef
- def equals(arg0: AnyRef): Boolean
- Definition Classes
- AnyRef → Any
- final def failed: Coeval[Throwable]
Returns a failed projection of this coeval.
Returns a failed projection of this coeval.
The failed projection is a
Coeval
holding a value of typeThrowable
, emitting the error yielded by the source, in case the source fails, otherwise if the source succeeds the result will fail with aNoSuchElementException
. - final def flatMap[B](f: (A) => Coeval[B]): Coeval[B]
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) }
- final def flatMapLoop[S](seed: S)(f: (A, S, (S) => Coeval[S]) => Coeval[S]): Coeval[S]
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) }
- seed
initializes the result of the loop
- f
is the function that updates the result on each iteration, returning a
Coeval
.- returns
a new Coeval that contains the result of the loop.
- final def flatten[B](implicit ev: <:<[A, Coeval[B]]): Coeval[B]
Given a source Coeval that emits another Coeval, this function flattens the result, returning a Coeval equivalent to the emitted Coeval by the source.
Given a source Coeval that emits another Coeval, this function flattens the result, returning a Coeval equivalent to the emitted Coeval by the source.
This equivalence with flatMap always holds:
fa.flatten <-> fa.flatMap(x => x)
- final def foreach(f: (A) => Unit): Unit
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.
- final def foreachL(f: (A) => Unit): Coeval[Unit]
Returns a new task that upon evaluation will execute the given function for the generated element, transforming the source into a
Coeval[Unit]
.Returns a new task that upon evaluation will execute the given function for the generated element, transforming the source into a
Coeval[Unit]
.Similar in spirit with normal foreach, but lazy, as obviously nothing gets executed at this point.
- final def getClass(): Class[_ <: AnyRef]
- Definition Classes
- AnyRef → Any
- Annotations
- @native() @HotSpotIntrinsicCandidate()
- final def guarantee(finalizer: Coeval[Unit]): Coeval[A]
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
- final def guaranteeCase(finalizer: (ExitCase[Throwable]) => Coeval[Unit]): Coeval[A]
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
- def hashCode(): Int
- Definition Classes
- AnyRef → Any
- Annotations
- @native() @HotSpotIntrinsicCandidate()
- final def isInstanceOf[T0]: Boolean
- Definition Classes
- Any
- final def map[B](f: (A) => B): Coeval[B]
Returns a new
Coeval
that applies the mapping function to the element emitted by the source.Returns a new
Coeval
that applies the mapping function to the element emitted by the source.Can be used for specifying a (lazy) transformation to the result of the source.
This equivalence with flatMap always holds:
fa.map(f) <-> fa.flatMap(x => Coeval.pure(f(x)))
- final def materialize: Coeval[Try[A]]
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.
- final def memoize: Coeval[A]
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.
- Annotations
- @UnsafeBecauseImpure()
- See also
memoizeOnSuccess for a version that only caches successful results
- final def memoizeOnSuccess: Coeval[A]
Memoizes (cache) the successful result of the source and reuses it on subsequent invocations of
value
.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.
- Annotations
- @UnsafeBecauseImpure()
- See also
memoize for a version that caches both successful results and failures
- final def ne(arg0: AnyRef): Boolean
- Definition Classes
- AnyRef
- final def notify(): Unit
- Definition Classes
- AnyRef
- Annotations
- @native() @HotSpotIntrinsicCandidate()
- final def notifyAll(): Unit
- Definition Classes
- AnyRef
- Annotations
- @native() @HotSpotIntrinsicCandidate()
- final def onErrorFallbackTo[B >: A](that: Coeval[B]): Coeval[B]
Creates a new coeval that in case of error will fallback to the given backup coeval.
- final def onErrorHandle[U >: A](f: (Throwable) => U): Coeval[U]
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.
- final def onErrorHandleWith[B >: A](f: (Throwable) => Coeval[B]): Coeval[B]
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.
- final def onErrorRecover[U >: A](pf: PartialFunction[Throwable, U]): Coeval[U]
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.
- final def onErrorRecoverWith[B >: A](pf: PartialFunction[Throwable, Coeval[B]]): Coeval[B]
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.
- final def onErrorRestart(maxRetries: Long): Coeval[A]
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
. - final def onErrorRestartIf(p: (Throwable) => Boolean): Coeval[A]
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
. - final def onErrorRestartLoop[S, B >: A](initial: S)(f: (Throwable, S, (S) => Coeval[B]) => Coeval[B]): Coeval[B]
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 2. the currentstate
, based on which a decision for the retry is made 3.retry: S => Task[B]
function that schedules the next retry
- initial
is the initial state used to determine the next on error retry cycle
- 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
- def redeem[B](recover: (Throwable) => B, map: (A) => B): Coeval[B]
Returns a new value that transforms the result of the source, given the
recover
ormap
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
ormap
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)
- recover
is a function used for error recover in case the source ends in error
- map
is a function used for mapping the result of the source in case it ends in success
- def redeemWith[B](recover: (Throwable) => Coeval[B], bind: (A) => Coeval[B]): Coeval[B]
Returns a new value that transforms the result of the source, given the
recover
orbind
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
orbind
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)
- recover
is the function that gets called to recover the source in case of error
- bind
is the function that gets to transform the source in case of success
- final def restartUntil(p: (A) => Boolean): Coeval[A]
Given a predicate function, keep retrying the coeval until the function returns true.
- def run(): Eager[A]
Evaluates the underlying computation, reducing this
Coeval
to a Coeval.Eager value, with successful results being signaled with Coeval.Now and failures with Coeval.Error.Evaluates the underlying computation, reducing this
Coeval
to a Coeval.Eager value, with successful results being signaled with Coeval.Now and failures with Coeval.Error.val fa = Coeval.eval(10 * 2) fa.run match { case Coeval.Now(value) => println("Success: " + value) case Coeval.Error(e) => e.printStackTrace() }
See runAttempt for working with Either values and runTry for working with Try values. See apply for a partial function (that may throw exceptions in case of failure).
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 Task, or at the edge of the FP program.- Annotations
- @UnsafeBecauseImpure()
- def runAttempt(): Either[Throwable, A]
Evaluates the underlying computation and returns the result or any triggered errors as a Scala
Either
, whereRight(_)
is for successful values andLeft(_)
is for thrown errors.Evaluates the underlying computation and returns the result or any triggered errors as a Scala
Either
, whereRight(_)
is for successful values andLeft(_)
is for thrown errors.val fa = Coeval(10 * 2) fa.runAttempt match { case Right(value) => println("Success: " + value) case Left(e) => e.printStackTrace() }
See run for working with Coeval.Eager values and runTry for working with Try values. See apply for a partial function (that may throw exceptions in case of failure).
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 Task, or at the edge of the FP program.- Annotations
- @UnsafeBecauseImpure()
- def runTry(): Try[A]
Evaluates the underlying computation and returns the result or any triggered errors as a
scala.util.Try
.Evaluates the underlying computation and returns the result or any triggered errors as a
scala.util.Try
.import scala.util._ val fa = Coeval(10 * 2) fa.runTry match { case Success(value) => println("Success: " + value) case Failure(e) => e.printStackTrace() }
See run for working with Coeval.Eager values and runAttempt for working with Either values. See apply for a partial function (that may throw exceptions in case of failure).
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 Task, or at the edge of the FP program.- Annotations
- @UnsafeBecauseImpure()
- final def synchronized[T0](arg0: => T0): T0
- Definition Classes
- AnyRef
- final def to[F[_]](implicit F: CoevalLift[F]): F[A]
Converts the source Coeval into any
F[_]
that implementscats.effect.Sync
.Converts the source Coeval into any
F[_]
that implementscats.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]
- def toString(): String
- Definition Classes
- Coeval → Function0 → AnyRef → Any
- final def toSync[F[_]](implicit F: Sync[F]): F[A]
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). - def value(): A
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 Task, or at the edge of the FP program.- Annotations
- @UnsafeBecauseImpure()
- final def void: Coeval[Unit]
Returns this coeval mapped to unit
- 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()
- final def wait(): Unit
- Definition Classes
- AnyRef
- Annotations
- @throws(classOf[java.lang.InterruptedException])
- final def zip[B](that: Coeval[B]): Coeval[(A, B)]
Zips the values of
this
andthat
coeval, and creates a new coeval that will emit the tuple of their results. - final def zipMap[B, C](that: Coeval[B])(f: (A, B) => C): Coeval[C]
Zips the values of
this
andthat
and applies the given mapping function on their results.
Deprecated Value Members
- def finalize(): Unit
- Attributes
- protected[lang]
- Definition Classes
- AnyRef
- Annotations
- @throws(classOf[java.lang.Throwable]) @Deprecated @deprecated
- Deprecated
(Since version ) see corresponding Javadoc for more information.
- final def transform[R](fa: (A) => R, fe: (Throwable) => R): Coeval[R]
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
onEither
and others (i.e. the function for error recovery is at the left).- Annotations
- @deprecated
- Deprecated
(Since version 3.0.0-RC2) Please use
Coeval.redeem
- final def transformWith[R](fa: (A) => Coeval[R], fe: (Throwable) => Coeval[R]): Coeval[R]
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
onEither
and others (i.e. the function for error recovery is at the left).- Annotations
- @deprecated
- Deprecated
(Since version 3.0.0-RC2) Please use
Coeval.redeemWith
This is the API documentation for the Monix library.
Package Overview
monix.execution exposes lower level primitives for dealing with asynchronous execution:
Atomic
types, as alternative tojava.util.concurrent.atomic
monix.catnap exposes pure abstractions built on top of the Cats-Effect type classes:
monix.eval is for dealing with evaluation of results, thus exposing Task and Coeval.
monix.reactive exposes the
Observable
pattern:Observable
implementationsmonix.tail exposes Iterant for purely functional pull based streaming:
Batch
andBatchCursor
, the alternatives to Scala'sIterable
andIterator
respectively that we are using within Iterant's encodingYou can control evaluation with type you choose - be it Task, Coeval, cats.effect.IO or your own as long as you provide correct cats-effect or cats typeclass instance.