2

假设我有一个函数列表,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] = ???

我想firecats

 import cats.implicits._

 subscribers.foldMap (_ map (_.toValidatedNel))
            .map (.toEither)
            .apply(e)

是否有意义 ?你会如何改进它?
如何更改fire为同时调用subscribers

4

1 回答 1

6

我可能会这样写:

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

于 2017-03-14T20:24:12.913 回答