最好的方法是将您的服务调用转换为使用cats-mtl
.
对于表示Try
或Option
您可以使用MonadError
,对于记录,您可以使用FunctorTell
. 现在我不知道你在userService
or中到底在做什么standService
,但我写了一些代码来演示结果可能是什么样子:
type Log = List[String]
//inside UserService
def findOneByEmail[F[_]](email: String)
(implicit F: MonadError[F, Error], W: FunctorTell[F, Log]): F[User] = ???
//inside StandService
def list[F[_]]()
(implicit F: MonadError[F, Error], W: FunctorTell[F, Log]): F[List[Stand]] = ???
def getStandsByUser[F[_]](email: String)
(implicit F: MonadError[F, Error], W: FunctorTell[F, Log]): F[List[Stand]] =
for {
user <- userService.findOneByEmail(email)
stands <- standService.list()
} yield stands.filter(stand => user.stands.contains(stand.id))
//here we actually run the function
val result =
getStandsByUser[WriterT[OptionT[Try, ?], Log, ?] // yields WriterT[OptionT[Try, ?], Log, List[Stand]]
.run // yields OptionT[Try, (Log, List[Stand])]
.value // yields Try[Option[(Log, List[Stand])]]
这样我们就可以避免所有对不同服务的调用liftF
并轻松组合我们的不同服务,即使它们在运行时会使用不同的 monad 转换器。