scala - 如何将源映射到另一个?
问题描述
我有两个案例类
case class Color (name: String, shades: List[Shade] = List.empty)
case class Shade (shadeName: String)
我也有两个解析器:
object ColorParser {
def apply(
s: String): Either[List[SomethingElse], Color] = {
val values = s.split("\\|", -1).map(_.trim).toList
validateColor(values).leftMap(xs => xs.toList).toEither
}
}
object ShadesParser {
def apply(s: String)
: Either[List[SomethingElse], Shade] = {
val values = s.split('|').map(_.trim).toList
validateShade(values).leftMap(xs => xs.toList).toEither
}
}
我有一个来源Color
和一个来源Shade
。
sourceForShade
.via (framing("\n"))
.map (_.utf8string)
.map (_.trim)
.map {
s => ShadesParser(s)
}
.collect {
case Right(shade) => shade
}
sourceForColor
.via(framing("\n"))
.map(_.utf8String)
.map(_.trim)
.map(s => ColorParser(s))
.collect {
case Right(color) => color
}
.map {color =>
//Here I want access to Color object that has the property shades list property set based on sourceForShade.
//At the moment it only has the name field but the List[Shade] property is empty.
}
问题
在 的评论部分map
,我如何才能访问一个颜色对象,该对象也具有shades: List[Shade]
基于填充的属性sourceForShade
解决方案
一种方法是首先Future[Seq[Shade]]
从第一个流中获取 a,然后将其结果应用于Future
第二个流:
val shades: Future[Seq[Shade]] =
sourceForShade
.via(framing("\n"))
.map(_.utf8String.trim)
.map(ShadesParser)
.collect {
case Right(shade) => shade
}
.runWith(Sink.seq[Shade])
val colors: Future[Source[Color, _]] =
shades map { s =>
sourceForColor
.via(framing("\n"))
.map(_.utf8String.trim)
.map(ColorParser)
.collect {
case Right(color) => color
}
.map(c => c.copy(shades = s.toList))
}
val colorsWithShades: Source[Color, _] =
Source.fromFuture(colors).flatMapConcat(identity)
推荐阅读
- javascript - React - getDerivedStateFromProps 和 axios
- hyperledger-fabric - 是否可以从 Fabric 客户端节点安装和使用 Hyperledger Explorer?
- python - 谷歌文档格式化,将文本转换成表格
- asp.net-core - 在 Dotnet Core 中获取针对 Google 身份验证的其他用户声明
- jquery - 无法使用 Response.Write 或 ClientScript.RegisterStartupScript 从代码后面打开新窗口
- asp.net - 在注册页面 ASP.NET Core 3.1 Identity 上填充下拉列表
- mysql - 子查询返回超过 1 行
- c# - 反序列化数组 json 的数组
- go - 如何在你的 go 文件中包含下载的 go 包
- python - 如何写入文件并每两条记录留一个空行?