Skip to content

Instantly share code, notes, and snippets.

@yasuabe
Created February 1, 2019 12:51
Show Gist options
  • Save yasuabe/d372faa11a8bf507d3f604bf185e8f96 to your computer and use it in GitHub Desktop.
Save yasuabe/d372faa11a8bf507d3f604bf185e8f96 to your computer and use it in GitHub Desktop.
Cats Effect Effect example
package cats_effect_typeclass_exericise.effect
import java.time.format.DateTimeFormatter
import cats.data.{Chain, WriterT}
import cats.effect._
import scala.language.higherKinds
object Util {
val formatter = DateTimeFormatter.ofPattern("mm:ss")
def putIn(milli: Int, s: Any): String = {
Thread.sleep(milli)
val threadId = Thread.currentThread.getId
val currentMinSec = java.time.LocalTime.now.format(formatter)
println(s"in thread($threadId) at $currentMinSec): $s")
s.toString
}
def putLine(s: Any): String = putIn(1000, s)
def putIn1Sec(s: Any): String = putIn(1000, s)
def putNow(s: Any): String = putIn(0, s)
def putRnd(s: Any): String = putIn((math.random * 1000 + 500).toInt, s)
}
import Util._
object EffectRunAsyncDemoApp extends IOApp {
def run(args: List[String]): IO[ExitCode] = {
// val task = IO.raiseError(new RuntimeException("dummy")) // prints "get error: 'dummy'"
val task = IO { putLine("IO body evaluated"); "Hello!" } // prints "got text: 'Hello!'"
val ioa: SyncIO[Unit] = Effect[IO].runAsync(task) {
case Right(text) => IO { putLine(s"got text: '$text'") }
case Left(th) => IO { putLine(s"got error: ${th.getMessage}") }
}
putLine("main thread")
ioa.toIO.map(_ => ExitCode.Success) // SyncIO has `toIO: IO`
}
// in thread(1) at 00:40): main thread
// in thread(11) at 00:41): IO body evaluated
// in thread(11) at 00:42): got text: 'Hello!'
//
// Process finished with exit code 0
}
object EffectWriterTDemoApp extends IOApp {
type WriterIO[T] = WriterT[IO, Chain[String], T]
val task = IO { putLine("IO body evaluated"); "Hello, WriterT!" }
def program(implicit E: Effect[WriterIO]) = for {
s <- E.liftIO(task)
_ <- WriterT.tell[IO, Chain[String]](Chain("a log line"))
} yield s
def run(args: List[String]): IO[ExitCode] = {
putLine("main thread")
program.run map { case (l, v) =>
putLine(s"value:$v, log: $l")
ExitCode.Success
}
}
// in thread(1) at 03:28): main thread
// in thread(11) at 03:30): IO body evaluated
// in thread(11) at 03:31): value:Hello, WriterT!, log: Chain(a log line)
//
// Process finished with exit code 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment