Mic*_*ael 2 concurrency scala monoids scala-cats
假设我有一个函数列表E => Either[Exception, Unit]来调用事件E并累积错误以返回Either[List[Exception], Unit].
type EventHandler = E => Either[Exception, Unit]
import cats.data.NonEmptyList
def fire(
e: Event,
subscribers: List[EventHandler]
): Either[NonEmptyList[Exception], Unit] = ???
Run Code Online (Sandbox Code Playgroud)
我想实现fire与cats
import cats.implicits._
subscribers.foldMap (_ map (_.toValidatedNel))
.map (.toEither)
.apply(e)
Run Code Online (Sandbox Code Playgroud)
是否有意义 ?你会如何改进它?
如何更改fire为subscribers同时调用?
我可能会这样写:
import cats.data.NonEmptyList, cats.implicits._
type Event = String
type EventHandler = Event => Either[Exception, Unit]
def fire(
e: Event,
subscribers: List[EventHandler]
): Either[NonEmptyList[Exception], Unit] =
subscribers.traverse_(_(e).toValidatedNel).toEither
Run Code Online (Sandbox Code Playgroud)
(如果你没有使用2.12.1或者不能使用-Ypartial-unification你需要traverseU_.)
如果你想让呼叫同时发生,通常你会达到EitherT[Future, Exception, _],但这不会给你你想要的错误累积.没有ValidatedT,但那是因为Applicative直接组成.所以你可以这样做:
import cats.Applicative
import cats.data.{ NonEmptyList, ValidatedNel }, cats.implicits._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
type Event = String
type EventHandler = Event => Future[Either[Exception, Unit]]
def fire(
e: Event,
subscribers: List[EventHandler]
): Future[Either[NonEmptyList[Exception], Unit]] =
Applicative[Future].compose[ValidatedNel[Exception, ?]].traverse(subscribers)(
_(e).map(_.toValidatedNel)
).map(_.void.toEither)
Run Code Online (Sandbox Code Playgroud)
(请注意,如果您不使用kind-projector,则需要写出lambda类型而不是使用?.)
并向自己证明它同时发生:
fire(
"a",
List(
s => Future { println(s"First: $s"); ().asRight },
s => Future { Thread.sleep(5000); println(s"Second: $s"); ().asRight },
s => Future { println(s"Third: $s"); ().asRight }
)
)
Run Code Online (Sandbox Code Playgroud)
你会看到First和Third马上.