Skip to content
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
55 lines (41 sloc) 1.59 KB
import{EitherT, WriterT}
import cats.implicits._
import monix.eval.Task
import scala.concurrent.Await
import scala.concurrent.duration._
object StackingMonadTransformers {
// Our error hierarchy
sealed trait ServiceError
case class UserNotFound(id: Int) extends ServiceError
case class OrderNotFound(user: User) extends ServiceError
case class User(id: Int)
case class Order(totalAmount: Int)
// Our custom monad stack
type OurStack[A] = WriterT[EitherT[Task, ServiceError, *], Vector[String], A]
def fetchUser(id: Int): OurStack[User] = {
val eitherT = EitherT.rightT[Task, ServiceError](User(id))
// we can use WriterT's apply method to build a WriterT from an F[(L, V)]
// i.e. a tuple, where L is the log and V is the value
val withLogs = => Vector("getting user") -> user)
def fetchOrder(user: User): OurStack[Order] = {
val eitherT = EitherT.rightT[Task, ServiceError](Order(100))
val withLogs = => Vector("getting order") -> user)
def main(args: Array[String]): Unit = {
val program = for {
user <- fetchUser(1)
order <- fetchOrder(user)
} yield order
val eventualLogs = program.written.value.runToFuture
val logs = Await.result(eventualLogs, 1.second)
val eventualResult = program.value.value.runToFuture
val result = Await.result(eventualResult, 1.second)
You can’t perform that action at this time.