如何处理将来的流以创建具有列表属性的类的实例

时间:2018-12-15 19:24:04

标签: scala akka akka-stream

我有一个方法,该方法将future作为参数,并且内部也包含future。我想从此方法创建一个列表,以便它从传入的将来获取值。

案例分类

case class Color (colorName: String)
case class Shade (shadeName: String)
case class ColoShade (color: Color, shades: List[Shade])

方法

val shadesFuture: Future[Seq[Shade]] = {
    val larSource: Future[Seq[LoanApplicationRegister]] =
      getMySource(ctx, id)
        .map(_.utf8String)
        .map(_.trim)
        .map(s => ShadeParser(s))
        .collect {
          case Right(shade) => shade
        }
        .runWith(Sink.seq)
}

//call the method
myMethod(shadesFuture)

//method definition
def myMethod(shadesFuture: Future[Seq][Shade]])
  :Future[ColorShade] {
    colorFuture
      .map(_.utf8String)
      .map(_.trim)
      .map { s =>
        ColorParser(s)
      }
      .collect {
        case Right(c) => c
      }
      .map { c =>  
         //How can I make an instance of ColorSade here? 
         //I tried 
         val colorShade = ColorShade(c, shadesFuture) 
         //but this doesn't work  

         //I would like to change this to instead be someOtherMethod(colorShade.c)
         someOtherMethod(c) 
      }
}

问题

如何正确地从ColorShade返回myMethod,以使shades属性是传入参数shadesFuture的输出?

1 个答案:

答案 0 :(得分:1)

我不确定我是否理解你的意思……但是我认为你正在寻找这样的东西:

 def myMethod(shadesFuture: Future[Seq[Shade]]) : Future[ColorShade] = for {
   shades <- shadesFuture
   color <- colorFuture.map(...) // whatever the transformations you wanted
   transformedColor = ColorParser(color.utf8String.trim) // or you can do them like this

   colorShade = ColorShade(color, shades)
   // whatever you wanted to do with it here
   _ = someOtherMethod(colorShade.c, colorShade.shades)
 } yield colorShade // or whatever you need to return. The result of this is `Future[ColorShade]`

这称为“理解”,对于一堆嵌套的.flatMap调用,在语法上是确定的。您也可以明确地编写它(这并不是理解所要理解的,但在功能上是等效的):

 shadesFuture
    .flatMap { shades => 
       colorFuture
         .map(...)  // transform, whatever
         .map(ColorShade(_, shades)
    }