Skip to content

Instantly share code, notes, and snippets.

@yasuabe
Created February 1, 2019 12:53
Show Gist options
  • Save yasuabe/f823c1fdaffb158c003f0f1067332dcc to your computer and use it in GitHub Desktop.
Save yasuabe/f823c1fdaffb158c003f0f1067332dcc to your computer and use it in GitHub Desktop.
Cats Effect ConcurrentEffect example
package cats_effect_typeclass_exericise.concurrent_effect
import java.time.format.DateTimeFormatter
import cats.data.{Chain, EitherT, 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 ConcurrentEffectRunCancelableDemo extends IOApp {
type EitherIO[T] = EitherT[IO, Throwable, T]
type WriterIO[T] = WriterT[IO, Chain[String], T]
val CEE: ConcurrentEffect[EitherIO] = implicitly[ConcurrentEffect[EitherIO]]
val CEW: ConcurrentEffect[WriterIO] = implicitly[ConcurrentEffect[WriterIO]]
def convert[F[_], G[_], A](fa: F[A])(implicit F: ConcurrentEffect[F], G: Concurrent[G]): G[A] = {
G.cancelable { cb =>
val token: CancelToken[F] = F.runCancelable(fa)(x => IO(cb(x))).unsafeRunSync()
convert[F, G, Unit](token)
}
}
def tell(line: String): WriterIO[Unit] = WriterT.tell(Chain(line))
override def run(args: List[String]): IO[ExitCode] = {
val a: EitherIO[String] = EitherT[IO, Throwable, String](IO(Right("1234")))
val b: WriterIO[String] = convert[EitherIO, WriterIO, String](a)
val d = for {
v <- b
_ <- tell("line A")
_ <- tell("line B")
} yield v
putLine("before run")
d.run.map { case (log, value) =>
putLine(s"value=$value: log=$log")
ExitCode.Success
}
}
// in thread(1) at 10:08): before run
// in thread(11) at 10:09): value=1234: log=Chain(line A, line B)
//
// Process finished with exit code 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment