sealed abstract class IO[+A] extends IOPlatform[A]
A pure abstraction representing the intention to perform a side effect, where the result of that side effect may be obtained synchronously (via return) or asynchronously (via callback).
IO values are pure, immutable values and thus preserve referential transparency, being
usable in functional programming. An IO is a data structure that represents just a
description of a side effectful computation.
IO can describe synchronous or asynchronous computations that:
- on evaluation yield exactly one result 2. can end in either success or failure and in
case of failure
flatMapchains get short-circuited (IOimplementing the algebra ofMonadError) 3. can be canceled, but note this capability relies on the user to provide cancelation logic
Effects described via this abstraction are not evaluated until the "end of the world", which is to say, when one of the "unsafe" methods are used. Effectful results are not memoized, meaning that memory overhead is minimal (and no leaks), and also that a single effect may be run multiple times in a referentially-transparent manner. For example:
val ioa = IO.println("hey!") val program = for { _ <- ioa _ <- ioa } yield () program.unsafeRunSync()
The above will print "hey!" twice, as the effect will be re-run each time it is sequenced in the monadic chain.
IO is trampolined in its flatMap evaluation. This means that you can safely call
flatMap in a recursive function of arbitrary depth, without fear of blowing the stack.
def fib(n: Int, a: Long = 0, b: Long = 1): IO[Long] = IO.pure(a + b) flatMap { b2 => if (n > 0) fib(n - 1, b, b2) else IO.pure(a) }
- Alphabetic
- By Inheritance
- IO
- IOPlatform
- Serializable
- AnyRef
- Any
- Hide All
- Show All
- Public
- Protected
Value Members
- final def !=(arg0: Any): Boolean
- Definition Classes
- AnyRef → Any
- def !>[B](that: IO[B]): IO[B]
- final def ##: Int
- Definition Classes
- AnyRef → Any
- def &>[B](that: IO[B]): IO[B]
Runs this IO and the parameter in parallel.
Runs this IO and the parameter in parallel.
Failure in either of the IOs will cancel the other one. If the whole computation is canceled, both actions are also canceled.
- def *>[B](that: IO[B]): IO[B]
Runs the current IO, then runs the parameter, keeping its result.
Runs the current IO, then runs the parameter, keeping its result. The result of the first action is ignored. If the source fails, the other action won't run. Not suitable for use when the parameter is a recursive reference to the current expression.
- See also
>> for the recursion-safe, lazily evaluated alternative
- def <&[B](that: IO[B]): IO[A]
Like &>, but keeps the result of the source
- def <*[B](that: IO[B]): IO[A]
Like *>, but keeps the result of the source.
- final def ==(arg0: Any): Boolean
- Definition Classes
- AnyRef → Any
- def >>[B](that: => IO[B]): IO[B]
Runs the current IO, then runs the parameter, keeping its result.
Runs the current IO, then runs the parameter, keeping its result. The result of the first action is ignored. If the source fails, the other action won't run. Evaluation of the parameter is done lazily, making this suitable for recursion.
- See also
[*>] for the strictly evaluated alternative
- def adaptError[E](pf: PartialFunction[Throwable, Throwable]): IO[A]
Transform certain errors using
pfand rethrow them.Transform certain errors using
pfand rethrow them. Non matching errors and successful values are not affected by this function.Implements
ApplicativeError.adaptError. - def andWait(duration: Duration): IO[A]
Returns an IO that will wait for the given duration after the execution of the source before returning the result.
Returns an IO that will wait for the given duration after the execution of the source before returning the result.
- duration
The duration to wait after executing the source
- def as[B](b: B): IO[B]
Replaces the result of this IO with the given value.
- final def asInstanceOf[T0]: T0
- Definition Classes
- Any
- def attempt: IO[Either[Throwable, A]]
Materializes any sequenced exceptions into value space, where they may be handled.
Materializes any sequenced exceptions into value space, where they may be handled.
This is analogous to the
catchclause intry/catch, being the inverse ofIO.raiseError. Thus:IO.raiseError(ex).attempt.unsafeRunSync() === Left(ex)
- See also
- def attemptTap[B](f: (Either[Throwable, A]) => IO[B]): IO[A]
Reifies the value or error of the source and performs an effect on the result, then recovers the original value or error back into
IO.Reifies the value or error of the source and performs an effect on the result, then recovers the original value or error back into
IO.Implements
MonadError.attemptTap. - def background: ResourceIO[IO[OutcomeIO[A]]]
Returns a resource that will start execution of this IO in the background.
Returns a resource that will start execution of this IO in the background.
In case the resource is closed while this IO is still running (e.g. due to a failure in
use), the background action will be canceled.- See also
cats.effect.kernel.GenSpawn#background for the generic version.
- def backgroundOn(ec: ExecutionContext): ResourceIO[IO[OutcomeIO[A]]]
- def backgroundOnExecutor(executor: Executor): ResourceIO[IO[OutcomeIO[A]]]
- def both[B](that: IO[B]): IO[(A, B)]
Runs the current and given IO in parallel, producing the pair of the results.
Runs the current and given IO in parallel, producing the pair of the results. If either fails with an error, the result of the whole will be that error and the other will be canceled.
- See also
bothOutcome for the version which produces the outcome of both effects executed in parallel
race for the version which produces the result of the winner and cancels the loser of the race
- def bothOutcome[B](that: IO[B]): IO[(OutcomeIO[A], OutcomeIO[B])]
Runs the current and given IO in parallel, producing the pair of the outcomes.
Runs the current and given IO in parallel, producing the pair of the outcomes. Both outcomes are produced, regardless of whether they complete successfully.
- See also
both for the version which embeds the outcomes to produce a pair of the results
raceOutcome for the version which produces the outcome of the winner and cancels the loser of the race
- def bracket[B](use: (A) => IO[B])(release: (A) => IO[Unit]): IO[B]
Returns an
IOaction that treats the source task as the acquisition of a resource, which is then exploited by theusefunction and thenreleased.Returns an
IOaction that treats the source task as the acquisition of a resource, which is then exploited by theusefunction and thenreleased.The
bracketoperation is the equivalent of thetry {} catch {} finally {}statements from mainstream languages.The
bracketoperation installs the necessary exception handler to release the resource in the event of an exception being raised during the computation, or in case of cancelation.If an exception is raised, then
bracketwill re-raise the exception after performing therelease. If the resulting task gets canceled, thenbracketwill still perform therelease, but the yielded task will be non-terminating (equivalent with IO.never).Example:
import java.io._ def readFile(file: File): IO[String] = { // Opening a file handle for reading text val acquire = IO(new BufferedReader( new InputStreamReader(new FileInputStream(file), "utf-8") )) acquire.bracket { in => // Usage part IO { // 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 IO(in.close()) } }
Note that in case of cancelation the underlying implementation cannot guarantee that the computation described by
usedoesn't end up executed concurrently with the computation fromrelease. In the example above that ugly Java loop might end up reading from aBufferedReaderthat is already closed due to the task being canceled, thus triggering an error in the background with nowhere to get signaled.In this particular example, given that we are just reading from a file, it doesn't matter. But in other cases it might matter, as concurrency on top of the JVM when dealing with I/O might lead to corrupted data.
For those cases you might want to do synchronization (e.g. usage of locks and semaphores) and you might want to use bracketCase, the version that allows you to differentiate between normal termination and cancelation.
NOTE on error handling: in case both the
releasefunction and theusefunction throws, the error raised byreleasegets signaled.For example:
val foo = new RuntimeException("Foo") val bar = new RuntimeException("Bar") IO("resource").bracket { _ => // use IO.raiseError(foo) } { _ => // release IO.raiseError(bar) }
In this case the resulting
IOwill raise errorfoo, while thebarerror gets reported on a side-channel. This is consistent with the behavior of Java's "Try with resources" except that no involved exceptions are mutated (i.e., in contrast to Java,barisn't added as a suppressed exception tofoo).- 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
bracketfunction- release
is a function that gets called after
useterminates, either normally or in error, or if it gets canceled, receiving as input the resource that needs to be released
- See also
- def bracketCase[B](use: (A) => IO[B])(release: (A, OutcomeIO[B]) => IO[Unit]): IO[B]
Returns a new
IOtask that treats the source task as the acquisition of a resource, which is then exploited by theusefunction and thenreleased, with the possibility of distinguishing between normal termination and cancelation, such that an appropriate release of resources can be executed.Returns a new
IOtask that treats the source task as the acquisition of a resource, which is then exploited by theusefunction and thenreleased, with the possibility of distinguishing between normal termination and cancelation, such that an appropriate release of resources can be executed.The
bracketCaseoperation is the equivalent oftry {} catch {} finally {}statements from mainstream languages when used for the acquisition and release of resources.The
bracketCaseoperation installs the necessary exception handler to release the resource in the event of an exception being raised during the computation, or in case of cancelation.In comparison with the simpler bracket version, this one allows the caller to differentiate between normal termination, termination in error and cancelation via an Outcome 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
useterminates, either normally or in error, or if it gets canceled, receiving as input the resource that needs release, along with the result ofuse(cancelation, error or successful result)
- See also
- def cancelable(fin: IO[Unit]): IO[A]
Given an effect which might be uncancelable and a finalizer, produce an effect which can be canceled by running the finalizer.
Given an effect which might be uncancelable and a finalizer, produce an effect which can be canceled by running the finalizer. This combinator is useful for handling scenarios in which an effect is inherently uncancelable but may be canceled through setting some external state. A trivial example of this might be the following:
val flag = new AtomicBoolean(false) val ioa = IO blocking { while (!flag.get()) { Thread.sleep(10) } } ioa.cancelable(IO.delay(flag.set(true)))
Without
cancelable, effects constructed byblocking,delay, and similar are inherently uncancelable. Simply adding anonCancelto such effects is insufficient to resolve this, despite the fact that under *some* circumstances (such as the above), it is possible to enrich an otherwise-uncancelable effect with early termination.cancelableaddresses this use-case.Note that there is no free lunch here. If an effect truly cannot be prematurely terminated,
cancelablewill not allow for cancelation. As an example, if you attempt to canceluncancelable(_ => never), the cancelation will hang forever (in other words, it will be itself equivalent tonever). Applyingcancelablewill not change this in any way. Thus, attempting to cancelcancelable(uncancelable(_ => never), unit)will also hang forever. As in all cases, cancelation will only return when all finalizers have run and the fiber has fully terminated.If the
IOself-cancels and thecancelableitself is uncancelable, the resulting fiber will be equal tonever(similar to race). Under normal circumstances, ifIOself-cancels, that cancelation will be propagated to the calling context.- fin
an effect which orchestrates some external state which terminates the
IO
- See also
- def clone(): AnyRef
- Attributes
- protected[lang]
- Definition Classes
- AnyRef
- Annotations
- @throws(classOf[java.lang.CloneNotSupportedException]) @native()
- def debug[B >: A](prefix: String = "DEBUG")(implicit S: Show[B] = Show.fromToString[B]): IO[A]
Logs the value of this
IO_(even if it is an error or if it was cancelled)_ to the standard output, using the implicitcats.Showinstance.Logs the value of this
IO_(even if it is an error or if it was cancelled)_ to the standard output, using the implicitcats.Showinstance.This operation is intended as a quick debug, not as proper logging.
- prefix
A custom prefix for the log message,
DEBUGis used as the default.
- def delayBy(duration: Duration): IO[A]
Returns an IO that will delay the execution of the source by the given duration.
Returns an IO that will delay the execution of the source by the given duration.
- duration
The duration to wait before executing the source
- final def eq(arg0: AnyRef): Boolean
- Definition Classes
- AnyRef
- def equals(arg0: AnyRef): Boolean
- Definition Classes
- AnyRef → Any
- def evalOn(ec: ExecutionContext): IO[A]
Shifts the execution of the current IO to the specified
ExecutionContext.Shifts the execution of the current IO to the specified
ExecutionContext. All stages of the execution will default to the pool in question, and any asynchronous callbacks will shift back to the pool upon completion. Any nested use ofevalOnwill override the specified pool. Once the execution fully completes, default control will be shifted back to the enclosing (inherited) pool.- See also
IO.executionContext for obtaining the
ExecutionContexton which the currentIOis being executed
- def evalOnExecutor(executor: Executor): IO[A]
Shifts the execution of the current IO to the specified java.util.concurrent.Executor.
Shifts the execution of the current IO to the specified java.util.concurrent.Executor.
- See also
- def finalize(): Unit
- Attributes
- protected[lang]
- Definition Classes
- AnyRef
- Annotations
- @throws(classOf[java.lang.Throwable])
- def flatMap[B](f: (A) => IO[B]): IO[B]
Monadic bind on
IO, used for sequentially composing twoIOactions, where the value produced by the firstIOis passed as input to a function producing the secondIOaction.Monadic bind on
IO, used for sequentially composing twoIOactions, where the value produced by the firstIOis passed as input to a function producing the secondIOaction.Due to this operation's signature,
flatMapforces a data dependency between twoIOactions, thus ensuring sequencing (e.g. one action to be executed before another one).Any exceptions thrown within the function will be caught and sequenced into the
IO, because due to the nature of asynchronous processes, without catching and handling exceptions, failures would be completely silent andIOreferences would never terminate on evaluation. - def flatTap[B](f: (A) => IO[B]): IO[A]
- def flatten[B](implicit ev: <:<[A, IO[B]]): IO[B]
- def forceR[B](that: IO[B]): IO[B]
- def foreverM: IO[Nothing]
Evaluates the current
IOin an infinite loop, terminating only on error or cancelation.Evaluates the current
IOin an infinite loop, terminating only on error or cancelation.IO.println("Hello, World!").foreverM // continues printing forever
- final def getClass(): Class[_ <: AnyRef]
- Definition Classes
- AnyRef → Any
- Annotations
- @native()
- def guarantee(finalizer: IO[Unit]): IO[A]
Executes the given
finalizerwhen the source is finished, either in success or in error, or if canceled.Executes the given
finalizerwhen the source is finished, either in success or in error, or if canceled.This variant of guaranteeCase evaluates the given
finalizerregardless of how the source gets terminated:- normal completion
- completion in error
- cancelation
This equivalence always holds:
io.guarantee(f) <-> IO.unit.bracket(_ => io)(_ => f)
- See also
guaranteeCase for the version that can discriminate between termination conditions
- def guaranteeCase(finalizer: (OutcomeIO[A]) => IO[Unit]): IO[A]
Executes the given
finalizerwhen the source is finished, either in success or in error, or if canceled, allowing for differentiating between exit conditions.Executes the given
finalizerwhen 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 Outcome in the provided function, allowing one to make a difference between:
- normal completion
- completion in error
- cancelation
This equivalence always holds:
io.guaranteeCase(f) <-> IO.unit.bracketCase(_ => io)((_, e) => f(e))
- See also
guarantee for the simpler version
- def handleError[B >: A](f: (Throwable) => B): IO[B]
- def handleErrorWith[B >: A](f: (Throwable) => IO[B]): IO[B]
Handle any error, potentially recovering from it, by mapping it to another
IOvalue.Handle any error, potentially recovering from it, by mapping it to another
IOvalue.Implements
ApplicativeError.handleErrorWith. - def hashCode(): Int
- Definition Classes
- AnyRef → Any
- Annotations
- @native()
- def ifM[B](ifTrue: => IO[B], ifFalse: => IO[B])(implicit ev: <:<[A, Boolean]): IO[B]
- final def isInstanceOf[T0]: Boolean
- Definition Classes
- Any
- def iterateUntil(p: (A) => Boolean): IO[A]
- def iterateWhile(p: (A) => Boolean): IO[A]
- def map[B](f: (A) => B): IO[B]
Functor map on
IO.Functor map on
IO. Given a mapping function, it transforms the value produced by the source, while keeping theIOcontext.Any exceptions thrown within the function will be caught and sequenced into the
IO. Due to the nature of asynchronous processes, without catching and handling exceptions, failures would be completely silent andIOreferences would never terminate on evaluation. - def memoize: IO[IO[A]]
- def metered(backpressure: Backpressure[IO]): IO[Option[A]]
Applies rate limiting to this
IObased on provided backpressure semantics.Applies rate limiting to this
IObased on provided backpressure semantics.- returns
an Option which denotes if this
IOwas run or not according to backpressure semantics
- 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: IO[Unit]): IO[A]
- def onError(pf: PartialFunction[Throwable, IO[Unit]]): IO[A]
Execute a callback on certain errors, then rethrow them.
Execute a callback on certain errors, then rethrow them. Any non matching error is rethrown as well.
Implements
ApplicativeError.onError. - def option: IO[Option[A]]
Replaces failures in this IO with an empty Option.
- def orElse[B >: A](other: => IO[B]): IO[B]
Runs the current IO, if it fails with an error(exception), the other IO will be executed.
Runs the current IO, if it fails with an error(exception), the other IO will be executed.
- other
IO to be executed (if the current IO fails)
- def parProduct[B](iob: IO[B])(implicit P: NonEmptyParallel[IO]): IO[(A, B)]
Like
Parallel.parProduct - def parProductL[B](iob: IO[B])(implicit P: NonEmptyParallel[IO]): IO[A]
Like
Parallel.parProductL - def parProductR[B](iob: IO[B])(implicit P: NonEmptyParallel[IO]): IO[B]
Like
Parallel.parProductR - def parReplicateA(n: Int): IO[List[A]]
Like
Parallel.parReplicateA - def parReplicateA_(n: Int): IO[Unit]
Like
Parallel.parReplicateA_ - def product[B](that: IO[B]): IO[(A, B)]
- def productL[B](that: IO[B]): IO[A]
- def productR[B](that: IO[B]): IO[B]
- def race[B](that: IO[B]): IO[Either[A, B]]
- def raceOutcome[B](that: IO[B]): IO[Either[OutcomeIO[A], OutcomeIO[B]]]
- def racePair[B](that: IO[B]): IO[Either[(OutcomeIO[A], FiberIO[B]), (FiberIO[A], OutcomeIO[B])]]
- def recover[B >: A](pf: PartialFunction[Throwable, B]): IO[B]
Recover from certain errors by mapping them to an
Avalue.Recover from certain errors by mapping them to an
Avalue.Implements
ApplicativeError.recover. - def recoverWith[B >: A](pf: PartialFunction[Throwable, IO[B]]): IO[B]
Recover from certain errors by mapping them to another
IOvalue.Recover from certain errors by mapping them to another
IOvalue.Implements
ApplicativeError.recoverWith. - def redeem[B](recover: (Throwable) => B, map: (A) => B): IO[B]
Returns a new value that transforms the result of the source, given the
recoverormapfunctions, which get executed depending on whether the result ends in error or if it is successful.Returns a new value that transforms the result of the source, given the
recoverormapfunctions, which get executed depending on whether the result ends in error or if it is successful.This is an optimization on usage of attempt and map, this equivalence being true:
io.redeem(recover, map) <-> io.attempt.map(_.fold(recover, map))Usage of
redeemsubsumeshandleErrorbecause:io.redeem(fe, id) <-> io.handleError(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) => IO[B], bind: (A) => IO[B]): IO[B]
Returns a new value that transforms the result of the source, given the
recoverorbindfunctions, which get executed depending on whether the result ends in error or if it is successful.Returns a new value that transforms the result of the source, given the
recoverorbindfunctions, which get executed depending on whether the result ends in error or if it is successful.This is an optimization on usage of attempt and flatMap, this equivalence being available:
io.redeemWith(recover, bind) <-> io.attempt.flatMap(_.fold(recover, bind))Usage of
redeemWithsubsumeshandleErrorWithbecause:io.redeemWith(fe, F.pure) <-> io.handleErrorWith(fe)Usage of
redeemWithalso subsumes flatMap because:io.redeemWith(F.raiseError, fs) <-> io.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
- def replicateA(n: Int): IO[List[A]]
- def replicateA_(n: Int): IO[Unit]
- def rethrow[B](implicit ev: <:<[A, Either[Throwable, B]]): IO[B]
Inverse of
attemptInverse of
attemptThis function raises any materialized error.
IO(Right(a)).rethrow === IO.pure(a) IO(Left(ex)).rethrow === IO.raiseError(ex) // Or more generally: io.attempt.rethrow === io // For any io.
- See also
- def start: IO[FiberIO[A]]
Start execution of the source suspended in the
IOcontext.Start execution of the source suspended in the
IOcontext.This can be used for non-deterministic / concurrent execution. The following code is more or less equivalent with
parMap2(minus the behavior on error handling and cancelation):def par2[A, B](ioa: IO[A], iob: IO[B]): IO[(A, B)] = for { fa <- ioa.start fb <- iob.start a <- fa.join b <- fb.join } yield (a, b)
Note in such a case usage of
parMapN(viacats.Parallel) is still recommended because of behavior on error and cancelation — consider in the example above what would happen if the first task finishes in error. In that case the second task doesn't get canceled, which creates a potential memory leak.Also see background for a safer alternative.
- def startOn(ec: ExecutionContext): IO[FiberIO[A]]
- def startOnExecutor(executor: Executor): IO[FiberIO[A]]
- def supervise(supervisor: Supervisor[IO]): IO[Fiber[IO, Throwable, A]]
Starts this
IOon the supervisor.Starts this
IOon the supervisor.- returns
a cats.effect.kernel.Fiber that represents a handle to the started fiber.
- def syncStep(limit: Int): SyncIO[Either[IO[A], A]]
Translates this
IO[A]into aSyncIOvalue which, when evaluated, runs the originalIOto its completion, thelimitnumber of stages, or until the first stage that cannot be expressed withSyncIO(typically an asynchronous boundary).Translates this
IO[A]into aSyncIOvalue which, when evaluated, runs the originalIOto its completion, thelimitnumber of stages, or until the first stage that cannot be expressed withSyncIO(typically an asynchronous boundary).- limit
The maximum number of stages to evaluate prior to forcibly yielding to
IO
- final def synchronized[T0](arg0: => T0): T0
- Definition Classes
- AnyRef
- def timed: IO[(FiniteDuration, A)]
- def timeout[A2 >: A](duration: Duration): IO[A2]
Returns an IO that either completes with the result of the source or otherwise raises a
TimeoutException.Returns an IO that either completes with the result of the source or otherwise raises a
TimeoutException.The source is raced against the timeout
duration, and its cancelation is triggered if the source doesn't complete within the specified time. The resulting effect will always wait for the source effect to complete (and to complete its finalizers), and will return the source's outcome over raising aTimeoutException.In case source and timeout complete simultaneously, the result of the source will be returned over raising a
TimeoutException.If the source effect is uncancelable, a
TimeoutExceptionwill never be raised.- duration
is the time span for which we wait for the source to complete before triggering its cancelation; in the event that the specified time has passed without the source completing, a
TimeoutExceptionis raised
- See also
timeoutAndForget for a variant which does not wait for cancelation of the source effect to complete.
- def timeoutAndForget(duration: Duration): IO[A]
Returns an IO that either completes with the result of the source within the specified time
durationor otherwise raises aTimeoutException.Returns an IO that either completes with the result of the source within the specified time
durationor otherwise raises aTimeoutException.The source is canceled in the event that it takes longer than the specified time duration to complete. Unlike timeout, the cancelation of the source will be requested but not awaited, and the exception will be raised immediately upon the completion of the timer. This may more closely match intuitions about timeouts, but it also violates backpressure guarantees and intentionally leaks fibers.
This combinator should be applied very carefully.
- duration
The time span for which we wait for the source to complete; in the event that the specified time has passed without the source completing, a
TimeoutExceptionis raised
- See also
timeout for a variant which respects backpressure and does not leak fibers
- def timeoutTo[A2 >: A](duration: Duration, fallback: IO[A2]): IO[A2]
Returns an IO that either completes with the result of the source or otherwise evaluates the
fallback.Returns an IO that either completes with the result of the source or otherwise evaluates the
fallback.The source is raised against the timeout
duration, and its cancelation is triggered if the source doesn't complete within the specified time. The resulting effect will always wait for the source effect to complete (and to complete its finalizers), and will return the source's outcome over sequencing thefallback.In case source and timeout complete simultaneously, the result of the source will be returned over sequencing the
fallback.If the source in uncancelable,
fallbackwill never be evaluated.- duration
is the time span for which we wait for the source to complete before triggering its cancelation; in the event that the specified time has passed without the source completing, the
fallbackgets evaluated- fallback
is the task evaluated after the duration has passed and the source canceled
- def to[F[_]](implicit F: LiftIO[F]): F[A]
Converts the source
IOinto anyFtype that implements the LiftIO type class. - def toResource: Resource[IO, A]
Lifts this
IOinto a resource.Lifts this
IOinto a resource. The resource has a no-op release. - def toString(): String
- Definition Classes
- IO → AnyRef → Any
- def uncancelable: IO[A]
Makes the source
IOuninterruptible such that a cats.effect.kernel.Fiber#cancel signal is ignored until completion.Makes the source
IOuninterruptible such that a cats.effect.kernel.Fiber#cancel signal is ignored until completion.- See also
IO.uncancelable for constructing uncancelable
IOvalues with user-configurable cancelable regions
- def unsafeRunAndForget()(implicit runtime: IORuntime): Unit
Triggers the evaluation of the source and any suspended side effects therein, but ignores the result.
Triggers the evaluation of the source and any suspended side effects therein, but ignores the result.
This operation is similar to unsafeRunAsync, in that the evaluation can happen asynchronously, except no callback is required and therefore the result is ignored.
Note that errors still get logged (via IO's internal logger), because errors being thrown should never be totally silent.
- def unsafeRunAsync(cb: (Either[Throwable, A]) => Unit)(implicit runtime: IORuntime): Unit
Passes the result of the encapsulated effects to the given callback by running them as impure side effects.
Passes the result of the encapsulated effects to the given callback by running them as impure side effects.
Any exceptions raised within the effect will be passed to the callback in the
Either. The callback will be invoked at most *once*. In addition, fatal errors will be printed. Note that it is very possible to construct an IO which never returns while still never blocking a thread, and attempting to evaluate that IO with this method will result in a situation where the callback is *never* invoked.As the name says, this is an UNSAFE function as it is impure and performs side effects. You should ideally only call this function once, at the very end of your program.
- def unsafeRunAsyncOutcome(cb: (Outcome[Id, Throwable, A]) => Unit)(implicit runtime: IORuntime): Unit
- def unsafeRunCancelable()(implicit runtime: IORuntime): () => Future[Unit]
Evaluates the effect, returning a cancelation token that can be used to cancel it.
Evaluates the effect, returning a cancelation token that can be used to cancel it.
This is similar to
unsafeRunAsyncin that it evaluates theIOas a side effect in a non-blocking fashion, but uses aFuturerather than an explicit callback. This function should really only be used if interoperating with code which uses Scala futures.- See also
- final def unsafeRunSync()(implicit runtime: IORuntime): A
Produces the result by running the encapsulated effects as impure side effects.
Produces the result by running the encapsulated effects as impure side effects.
If any component of the computation is asynchronous, the current thread will block awaiting the results of the async computation. By default, this blocking will be unbounded. To limit the thread block to some fixed time, use
unsafeRunTimedinstead.Any exceptions raised within the effect will be re-thrown during evaluation.
As the name says, this is an UNSAFE function as it is impure and performs side effects, not to mention blocking, throwing exceptions, and doing other things that are at odds with reasonable software. You should ideally only call this function *once*, at the very end of your program.
- Definition Classes
- IOPlatform
- final def unsafeRunTimed(limit: FiniteDuration)(implicit runtime: IORuntime): Option[A]
Similar to
unsafeRunSync, except with a bounded blocking duration when awaiting asynchronous results.Similar to
unsafeRunSync, except with a bounded blocking duration when awaiting asynchronous results. As soon as an async blocking limit is hit, evaluation immediately aborts andNoneis returned. Note that this does not backpressure on the completion of finalizers, which makes it quite different (and less safe) than other mechanisms for limiting evaluation time.val program: IO[A] = ... program.timeout(5.seconds).unsafeRunSync() program.unsafeRunTimed(5.seconds)
The first line will run
programfor at most five seconds, interrupt the calculation, and run the finalizers for as long as they need to complete. The second line will runprogramfor at most five seconds, start its finalizers, but then immediately release the latch.In other words, this function probably doesn't do what you think it does, and you probably don't want to use it outside of tests.
- Definition Classes
- IOPlatform
- See also
IO.timeout for pure and safe version
- final def unsafeToCompletableFuture()(implicit runtime: IORuntime): CompletableFuture[A]
- Definition Classes
- IOPlatform
- def unsafeToFuture()(implicit runtime: IORuntime): Future[A]
Evaluates the effect and produces the result in a
Future.Evaluates the effect and produces the result in a
Future.This is similar to
unsafeRunAsyncin that it evaluates theIOas a side effect in a non-blocking fashion, but uses aFuturerather than an explicit callback. This function should really only be used if interoperating with code which uses Scala futures.- See also
- def unsafeToFutureCancelable()(implicit runtime: IORuntime): (Future[A], () => Future[Unit])
Evaluates the effect and produces the result in a
Future, along with a cancelation token that can be used to cancel the original effect.Evaluates the effect and produces the result in a
Future, along with a cancelation token that can be used to cancel the original effect.This is similar to
unsafeRunAsyncin that it evaluates theIOas a side effect in a non-blocking fashion, but uses aFuturerather than an explicit callback. This function should really only be used if interoperating with code which uses Scala futures.- See also
- def untilM[G[_], B >: A](cond: => IO[Boolean])(implicit arg0: Alternative[G]): IO[G[B]]
- def untilM_(cond: => IO[Boolean]): IO[Unit]
- def void: IO[Unit]
Ignores the result of this IO.
- def voidError(implicit ev: <:<[A, Unit]): IO[Unit]
Discard any error raised by the source.
- 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()
- def whileM[G[_], B >: A](p: IO[Boolean])(implicit arg0: Alternative[G]): IO[G[B]]
- def whileM_(p: IO[Boolean]): IO[Unit]