Skip to content

Instantly share code, notes, and snippets.

@ShahOdin
Last active November 3, 2019 01:14
Show Gist options
  • Save ShahOdin/7939932f74c2f99ae541722b378ccc05 to your computer and use it in GitHub Desktop.
Save ShahOdin/7939932f74c2f99ae541722b378ccc05 to your computer and use it in GitHub Desktop.
two examples of resource management scenarios
package com.itv.sif.db
import cats.effect.IOApp
import java.util.concurrent.Executors
import fs2.Stream
import cats.syntax.functor._
import scala.concurrent.ExecutionContext
import cats.effect._
object Toolbox {
def blockingThreadPool[F[_]](implicit F: Sync[F]): Resource[F, ExecutionContext] =
Resource(F.delay {
val executor = Executors.newCachedThreadPool()
val ec = ExecutionContext.fromExecutor(executor)
println("getting the resource ")
(ec, F.delay(executor.shutdown()))
})
def blockingWork[F[_]](implicit F: Sync[F]): F[String] = F.delay {
println("Enter your name: ")
scala.io.StdIn.readLine()
}
def allocateResourcesAndDoWork[F[_]: Sync: Bracket[*, Throwable]](r: Resource[F, ExecutionContext])(
implicit cs: ContextShift[F]
): F[String] = r.use { ec =>
cs.evalOn(ec)(blockingWork[F])
}
def useResourcesAndDoWork[F](ec: ExecutionContext)(implicit cs: ContextShift[F]) = cs.evalOn(ec)(blockingWork[IO])
}
object TestDemo extends IOApp {
def resourceRecipe: Resource[IO, ExecutionContext] = Toolbox.blockingThreadPool[IO]
def eachProcessHasItsOwnResource: IO[ExitCode] = for {
n <- Toolbox.allocateResourcesAndDoWork(resourceRecipe)
m <- Toolbox.allocateResourcesAndDoWork(resourceRecipe)
_ <- IO(println(s"Hello, $n and $m!"))
} yield ExitCode.Success
def processesSharedResource: IO[ExitCode] = {
def stream: Stream[IO, ExitCode] = for {
resource <- Stream.resource(resourceRecipe)
n <- Stream.eval(Toolbox.useResourcesAndDoWork(resource))
m <- Stream.eval(Toolbox.useResourcesAndDoWork(resource))
_ <- Stream.eval(IO(println(s"Hello, $n and $m!")))
} yield ExitCode.Success
stream.compile.drain.as(ExitCode.Success)
}
def run(args: List[String]): IO[ExitCode] = processesSharedResource
//def run(args: List[String]): IO[ExitCode] = eachProcessHasItsOwnResource
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment