Skip to content

Instantly share code, notes, and snippets.

@xuwei-k
Created October 7, 2019 01:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xuwei-k/6a9cd96a6aedc5c686e2d57f146f375f to your computer and use it in GitHub Desktop.
Save xuwei-k/6a9cd96a6aedc5c686e2d57f146f375f to your computer and use it in GitHub Desktop.
libraryDependencies += "org.typelevel" %% "cats-effect" % "2.0.0"
scalaVersion := "2.13.1"
package example
import cats.effect.concurrent.Ref
import cats.effect._
import cats.syntax.traverse._
import cats.instances.list._
// https://github.com/typelevel/cats-effect/blob/v2.0.0/core/shared/src/main/scala/cats/effect/concurrent/Ref.scala#L208
object CatsRefUnsafeExample extends IOApp {
override def run(args: List[String]) = {
val unsafe = {
val x = Ref.unsafe[IO, Int](0)
for {
_ <- x.update(_ + 1)
a <- x.get
} yield {
println("unsafe = " + a)
a
}
}
val safe = {
for {
x <- Ref[IO].of(0)
_ <- x.update(_ + 1)
a <- x.get
} yield {
println("safe = " + a)
a
}
}
List(unsafe, unsafe, unsafe, safe, safe, safe).sequence.map{ _ =>
ExitCode.Success
}
}
}
[info] running example.CatsRefUnsafeExample
unsafe = 1
unsafe = 2
unsafe = 3
safe = 1
safe = 1
safe = 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment