SyncIO
A pure abstraction representing the intention to perform a side effect, where the result of that side effect is obtained synchronously.
SyncIO
is similar to IO, but does not support asynchronous computations. Consequently, a SyncIO
can be run synchronously to obtain a result via unsafeRunSync
. This is unlike IO#unsafeRunSync
, which cannot be safely called in general. Doing so on the JVM blocks the calling thread while the async part of the computation is run and doing so on Scala.js throws an exception upon encountering an async boundary.
Constructing SyncIO values
import cats.effect.SyncIO
def putStrLn(str: String): SyncIO[Unit] = SyncIO(println(str))
SyncIO.pure("Cats!").flatMap(putStrLn).unsafeRunSync()
// Cats!
There's also suspend
and unit
, equivalent to the same operations defined in IO
but with synchronicity guarantees.
Interoperation with Eval and IO
SyncIO
defines an eval
method in its companion object to lift any cats.Eval
value.
import cats.Eval
val eval = Eval.now("hey!")
// eval: Eval[String] = Now(value = "hey!")
SyncIO.eval(eval).unsafeRunSync()
// res1: String = "hey!"
SyncIO
also defines a to[F]
method at the class level to lift your value into any F
with a LiftIO
instance available.
import cats.effect.IO
val ioa: SyncIO[Unit] = SyncIO(println("Hello world!"))
// ioa: SyncIO[Unit] = SyncIO$1068693761
val iob: IO[Unit] = ioa.to[IO]
// iob: IO[Unit] = Delay(
// thunk = <function0>,
// trace = StackTrace(
// stackTrace = List(
// cats.effect.internals.IOTracing$.buildFrame(IOTracing.scala:48),
// cats.effect.internals.IOTracing$.buildCachedFrame(IOTracing.scala:39),
// cats.effect.internals.IOTracing$.cached(IOTracing.scala:34),
// cats.effect.IO$.delay(IO.scala:1176),
// cats.effect.IO$.apply(IO.scala:1144),
// cats.effect.SyncIO$.apply(SyncIO.scala:330),
// repl.MdocSession$App.<init>(syncio.md:35),
// repl.MdocSession$.app(syncio.md:3),
// mdoc.internal.document.DocumentBuilder$$doc$.$anonfun$build$2(DocumentBuilder.scala:89),
// scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.scala:18),
// scala.util.DynamicVariable.withValue(DynamicVariable.scala:59),
// scala.Console$.withErr(Console.scala:193),
// mdoc.internal.document.DocumentBuilder$$doc$.$anonfun$build$1(DocumentBuilder.scala:89),
// scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.scala:18),
// scala.util.DynamicVariable.withValue(DynamicVariable.scala:59),
// scala.Console$.withOut(Console.scala:164),
// mdoc.internal.document.DocumentBuilder$$doc$.build(DocumentBuilder.scala:88),
// mdoc.internal.markdown.MarkdownBuilder$.$anonfun$buildDocument$2(MarkdownBuilder.scala:47),
// mdoc.internal.markdown.MarkdownBuilder$$anon$1.run(MarkdownBuilder.scala:104)
// )
// )
// )
iob.unsafeRunAsync(_ => ())
// Hello world!