Packages

sealed abstract class IO[+A] extends IOBinaryCompat[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).

Effects contained within 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 for all synchronous joins. This means that you can safely call flatMap in a recursive function of arbitrary depth, without fear of blowing the stack. However, IO cannot guarantee stack-safety in the presence of arbitrarily nested asynchronous suspensions. This is quite simply because it is impossible (on the JVM) to guarantee stack-safety in that case. For example:

def lie[A]: IO[A] = IO.async(cb => cb(Right(lie))).flatMap(a => a)

This should blow the stack when evaluated. Also note that there is no way to encode this using tailRecM in such a way that it does not blow the stack. Thus, the tailRecM on Monad[IO] is not guaranteed to produce an IO which is stack-safe when run, but will rather make every attempt to do so barring pathological structure.

IO makes no attempt to control finalization or guaranteed resource-safety in the presence of concurrent preemption, simply because IO does not care about concurrent preemption at all! IO actions are not interruptible and should be considered broadly-speaking atomic, at least when used purely.

Source
IO.scala
Linear Supertypes
IOBinaryCompat[A], AnyRef, Any
Ordering
  1. Alphabetic
  2. By Inheritance
Inherited
  1. IO
  2. IOBinaryCompat
  3. AnyRef
  4. Any
  1. Hide All
  2. Show All
Visibility
  1. Public
  2. All

Value Members

  1. final def !=(arg0: Any): Boolean
    Definition Classes
    AnyRef → Any
  2. final def ##(): Int
    Definition Classes
    AnyRef → Any
  3. final def ==(arg0: Any): Boolean
    Definition Classes
    AnyRef → Any
  4. final def asInstanceOf[T0]: T0
    Definition Classes
    Any
  5. 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 catch clause in try/catch, being the inverse of IO.raiseError. Thus:

    IO.raiseError(ex).attempt.unsafeRunAsync === Left(ex)
    See also

    IO.raiseError

  6. def clone(): AnyRef
    Attributes
    protected[java.lang]
    Definition Classes
    AnyRef
    Annotations
    @native() @throws( ... )
  7. final def eq(arg0: AnyRef): Boolean
    Definition Classes
    AnyRef
  8. def equals(arg0: Any): Boolean
    Definition Classes
    AnyRef → Any
  9. def finalize(): Unit
    Attributes
    protected[java.lang]
    Definition Classes
    AnyRef
    Annotations
    @throws( classOf[java.lang.Throwable] )
  10. final def flatMap[B](f: (A) ⇒ IO[B]): IO[B]

    Monadic bind on IO, used for sequentially composing two IO actions, where the value produced by the first IO is passed as input to a function producing the second IO action.

    Monadic bind on IO, used for sequentially composing two IO actions, where the value produced by the first IO is passed as input to a function producing the second IO action.

    Due to this operation's signature, flatMap forces a data dependency between two IO actions, 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 and IO references would never terminate on evaluation.

  11. final def getClass(): Class[_]
    Definition Classes
    AnyRef → Any
    Annotations
    @native()
  12. def hashCode(): Int
    Definition Classes
    AnyRef → Any
    Annotations
    @native()
  13. final def isInstanceOf[T0]: Boolean
    Definition Classes
    Any
  14. final def map[B](f: (A) ⇒ B): IO[B]

    Functor map on IO.

    Functor map on IO. Given a mapping functions, it transforms the value produced by the source, while keeping the IO context.

    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 and IO references would never terminate on evaluation.

  15. final def ne(arg0: AnyRef): Boolean
    Definition Classes
    AnyRef
  16. final def notify(): Unit
    Definition Classes
    AnyRef
    Annotations
    @native()
  17. final def notifyAll(): Unit
    Definition Classes
    AnyRef
    Annotations
    @native()
  18. final def onCancelRaiseError(e: Throwable): IO[A]

    Returns a new IO that mirrors the source task for normal termination, but that triggers the given error on cancellation.

    Returns a new IO that mirrors the source task for normal termination, but that triggers the given error on cancellation.

    Normally tasks that are cancelled become non-terminating.

    This onCancelRaiseError operator transforms a task that is non-terminating on cancellation into one that yields an error, thus equivalent with IO.raiseError.

  19. final def runAsync(cb: (Either[Throwable, A]) ⇒ IO[Unit]): IO[Unit]

    Produces an IO reference that should execute the source on evaluation, without waiting for its result, being the safe analogue to unsafeRunAsync.

    Produces an IO reference that should execute the source on evaluation, without waiting for its result, being the safe analogue to unsafeRunAsync.

    This operation is isomorphic to unsafeRunAsync. What it does is to let you describe asynchronous execution with a function that stores off the results of the original IO as a side effect, thus avoiding the usage of impure callbacks or eager evaluation.

    The returned IO is guaranteed to execute immediately, and does not wait on any async action to complete, thus this is safe to do, even on top of runtimes that cannot block threads (e.g. JavaScript):

    // Sample
    val source = IO.shift *> IO(1)
    // Describes execution
    val start = source.runAsync
    // Safe, because it does not block for the source to finish
    start.unsafeRunSync
    returns

    an IO value that upon evaluation will execute the source, but will not wait for its completion

    See also

    runCancelable for the version that gives you a cancelable token that can be used to send a cancel signal

  20. final def runCancelable(cb: (Either[Throwable, A]) ⇒ IO[Unit]): IO[IO[Unit]]

    Produces an IO reference that should execute the source on evaluation, without waiting for its result and return a cancelable token, being the safe analogue to unsafeRunCancelable.

    Produces an IO reference that should execute the source on evaluation, without waiting for its result and return a cancelable token, being the safe analogue to unsafeRunCancelable.

    This operation is isomorphic to unsafeRunCancelable. Just like runAsync, this operation avoids the usage of impure callbacks or eager evaluation.

    The returned IO boxes an IO[Unit] that can be used to cancel the running asynchronous computation (if the source can be cancelled).

    The returned IO is guaranteed to execute immediately, and does not wait on any async action to complete, thus this is safe to do, even on top of runtimes that cannot block threads (e.g. JavaScript):

    val source: IO[Int] = ???
    // Describes interruptible execution
    val start: IO[IO[Unit]] = source.runCancelable
    
    // Safe, because it does not block for the source to finish
    val cancel: IO[Unit] = start.unsafeRunSync
    
    // Safe, because cancellation only sends a signal,
    // but doesn't back-pressure on anything
    cancel.unsafeRunSync
    returns

    an IO value that upon evaluation will execute the source, but will not wait for its completion, yielding a cancellation token that can be used to cancel the async process

    See also

    runAsync for the simple, uninterruptible version

  21. final def start: IO[Fiber[IO, A]]

    Start execution of the source suspended in the IO context.

    Start execution of the source suspended in the IO context.

    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 cancellation):

    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 (via cats.Parallel) is still recommended because of behavior on error and cancellation — consider in the example above what would happen if the first task finishes in error. In that case the second task doesn't get cancelled, which creates a potential memory leak.

    IMPORTANT — this operation does not start with an asynchronous boundary. But you can use IO.shift to force an async boundary just before start.

  22. final def synchronized[T0](arg0: ⇒ T0): T0
    Definition Classes
    AnyRef
  23. final def to[F[_]](implicit F: LiftIO[F]): F[A]

    Converts the source IO into any F type that implements the LiftIO type class.

  24. def toString(): String
    Definition Classes
    IO → AnyRef → Any
  25. final def uncancelable: IO[A]

    Makes the source Task uninterruptible such that a Fiber.cancel signal has no effect.

  26. final def unsafeRunAsync(cb: (Either[Throwable, A]) ⇒ Unit): 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*. 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.

  27. final def unsafeRunCancelable(cb: (Either[Throwable, A]) ⇒ Unit): () ⇒ Unit

    Evaluates the source IO, passing the result of the encapsulated effects to the given callback.

    Evaluates the source IO, passing the result of the encapsulated effects to the given callback.

    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.

    returns

    an side-effectful function that, when executed, sends a cancellation reference to IO's run-loop implementation, having the potential to interrupt it.

  28. final def unsafeRunSync(): 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. On JavaScript, an exception will be thrown instead to avoid generating a deadlock. By default, this blocking will be unbounded. To limit the thread block to some fixed time, use unsafeRunTimed instead.

    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.

  29. final def unsafeRunTimed(limit: Duration): 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.

    Please note that the limit parameter does not limit the time of the total computation, but rather acts as an upper bound on any *individual* asynchronous block. Thus, if you pass a limit of 5 seconds to an IO consisting solely of synchronous actions, the evaluation may take considerably longer than 5 seconds! Furthermore, if you pass a limit of 5 seconds to an IO consisting of several asynchronous actions joined together, evaluation may take up to n * 5 seconds, where n is the number of joined async actions.

    As soon as an async blocking limit is hit, evaluation immediately aborts and None is returned.

    Please note that this function is intended for testing; it should never appear in your mainline production code! It is absolutely not an appropriate function to use if you want to implement timeouts, or anything similar. If you need that sort of functionality, you should be using a streaming library (like fs2 or Monix).

    See also

    unsafeRunSync

  30. final def unsafeToFuture(): 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 unsafeRunAsync in that it evaluates the IO as a side effect in a non-blocking fashion, but uses a Future rather than an explicit callback. This function should really only be used if interoperating with legacy code which uses Scala futures.

    See also

    IO.fromFuture

  31. final def wait(): Unit
    Definition Classes
    AnyRef
    Annotations
    @throws( ... )
  32. final def wait(arg0: Long, arg1: Int): Unit
    Definition Classes
    AnyRef
    Annotations
    @throws( ... )
  33. final def wait(arg0: Long): Unit
    Definition Classes
    AnyRef
    Annotations
    @native() @throws( ... )

Inherited from IOBinaryCompat[A]

Inherited from AnyRef

Inherited from Any

Ungrouped