如何将一个源映射到另一个? [英] How to map a source onto another?

查看:108
本文介绍了如何将一个源映射到另一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个案例类

case class Color (name: String, shades: List[Shade] = List.empty)

case class Shade (shadeName: String)

我也有解析器对于这两者:

I also have parsers for both:

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
    }
}

我有一个颜色和 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.
  }

问题

贴图的注释部分中,如何获得也具有阴影的颜色对象:List [ Shade] 属性根据 sourceForShade

In the comments section for the map, how can I get access to a color object that also has shades: List[Shade] property populated based on sourceForShade

推荐答案

一种方法是先从第一个流中获取 Future [Seq [Shade]] ,然后应用该 Future 到第二个流:

One approach is to first obtain a Future[Seq[Shade]] from the first stream, then apply the result of that Future to the second stream:

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)

这篇关于如何将一个源映射到另一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆