Skip to content

Instantly share code, notes, and snippets.

@Tvaroh
Last active December 5, 2017 07:55
Show Gist options
  • Save Tvaroh/522169efa3eecd4eba7c92e164e9c0f9 to your computer and use it in GitHub Desktop.
Save Tvaroh/522169efa3eecd4eba7c92e164e9c0f9 to your computer and use it in GitHub Desktop.
TODO
import cats.{Monad, StackSafeMonad}
import cats.effect.{IO, LiftIO}
trait Session {
def close(): Unit
}
case class SessionContext[T](exec: Session => IO[T]) {
def runSession(newSession: () => Session): IO[T] = {
val session = newSession()
exec(session).map { t =>
session.close()
t
}
}
}
object SessionContext {
implicit val instance: Monad[SessionContext] with LiftIO[SessionContext] =
new StackSafeMonad[SessionContext] with LiftIO[SessionContext] {
override def pure[A](a: A): SessionContext[A] =
SessionContext(Function.const(IO.pure(a)))
override def flatMap[A, B](fa: SessionContext[A])
(f: A => SessionContext[B]): SessionContext[B] =
SessionContext(session => fa.exec(session).flatMap(a => f(a).exec(session)))
override def liftIO[A](io: IO[A]): SessionContext[A] =
SessionContext(Function.const(io))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment