我可能会这样写:
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
(如果您未使用 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)
(请注意,如果您不使用 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 }
)
)
您会立即看到First 和Third。