Skip to content

Instantly share code, notes, and snippets.

@yasuabe
Created January 31, 2019 10:30
Show Gist options
  • Save yasuabe/5f9d990a752ac91dca989927ae5c21d5 to your computer and use it in GitHub Desktop.
Save yasuabe/5f9d990a752ac91dca989927ae5c21d5 to your computer and use it in GitHub Desktop.
Cats Effect Sync demo
package cats_effect_typeclass_exericise.sync
import java.time.format.DateTimeFormatter
import cats.effect.{ExitCode, IO, IOApp, Sync}
import cats.instances.list._
import cats.syntax.parallel._
import cats.syntax.functor._
import cats.syntax.flatMap._
object Util {
private 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 SyncDemo extends IOApp {
override def run(args: List[String]): IO[ExitCode] = {
val ioa = Sync[IO].delay {
putNow("A begins")
putIn1Sec("A ends")
}
val iob = Sync[IO].suspend {
IO {
putNow("B begins")
putIn1Sec("B ends")
}
}
putNow("ioa and iob initialized.")
List(ioa, iob).parSequence.void >> IO(ExitCode.Success)
}
// in thread(1) at 18:37): ioa and iob initialized.
// in thread(11) at 18:37): A begins
// in thread(12) at 18:37): B begins
// in thread(11) at 18:38): A ends
// in thread(12) at 18:38): B ends
//
// Process finished with exit code 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment