在 akka 流中过滤掉 Either Left 的惯用方法是什么?
What is an idiomatic way to filter out Either Left in an akka stream?
我有一个流,其中包含大量任一值。我正在寻找一种符合逻辑的方法来过滤掉 Either-Left 并在 Either-Right 上进行映射。我想避免像
这样的事情
final case class Foo(x: Either[String, Int], y:Int)
val foos = functionReturningSeqOfFoo()
Source(foos)
.filter(_.x.isRight)
.map(foo => (foo.x.right.get, foo.y))
.map { case (x, y) =>
doSomethingWith(x, y)
}
.runWith(Sink.seq)
这是一个最小的例子。由于我的流很长,这变得很乱,而且感觉不是一个好方法。
顺便说一句,在我的情况下,这同样适用于 Option[T]。
您正在寻找 Flow.collect
:
Source(eithers)
.collect { case Foo(Right(x), y) => (x, y) }
.map { case (x, y) => doSomethingWith(x, y) }
.runWith(Sink.seq)
collect
,类似于 Scala 库,将偏函数应用于所有元素,returns 这些元素因为它的 isDefined
方法而产生 true。
您可以使用 collect:
Source(foos).collect { case Foo(Right(x), y) => (x, y) }
或使用以下方法直接转换元组:
Source(foos).collect { case Foo(Right(x), y) => doSomethingWith(x, y) }
collect
将删除所有未定义偏函数的对象。
我有一个流,其中包含大量任一值。我正在寻找一种符合逻辑的方法来过滤掉 Either-Left 并在 Either-Right 上进行映射。我想避免像
这样的事情final case class Foo(x: Either[String, Int], y:Int)
val foos = functionReturningSeqOfFoo()
Source(foos)
.filter(_.x.isRight)
.map(foo => (foo.x.right.get, foo.y))
.map { case (x, y) =>
doSomethingWith(x, y)
}
.runWith(Sink.seq)
这是一个最小的例子。由于我的流很长,这变得很乱,而且感觉不是一个好方法。
顺便说一句,在我的情况下,这同样适用于 Option[T]。
您正在寻找 Flow.collect
:
Source(eithers)
.collect { case Foo(Right(x), y) => (x, y) }
.map { case (x, y) => doSomethingWith(x, y) }
.runWith(Sink.seq)
collect
,类似于 Scala 库,将偏函数应用于所有元素,returns 这些元素因为它的 isDefined
方法而产生 true。
您可以使用 collect:
Source(foos).collect { case Foo(Right(x), y) => (x, y) }
或使用以下方法直接转换元组:
Source(foos).collect { case Foo(Right(x), y) => doSomethingWith(x, y) }
collect
将删除所有未定义偏函数的对象。