How to map a source onto another?

感情迁移 提交于 2020-01-16 13:18:06

问题


I have two case classes

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

I have a source for Color and a source for 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.
  }

Question

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


回答1:


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)


来源:https://stackoverflow.com/questions/53794892/how-to-map-a-source-onto-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!