如何处理未来流以使用列表 属性 创建 class 的实例

How to process future stream to create an instance of class with list property

我有一个方法,它将未来作为参数,并且在其中也有未来。我想从此方法创建一个列表,以便它从传入的未来获取值。

案例类

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

问题

如何从 myMethod 正确地 return ColorShade 使得 shades 属性 是传入参数 [=17= 的输出]?

我不确定我明白你的意思......但我认为你正在寻找这样的东西:

 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]`

这称为 "for-comprehension" 并且对于一堆嵌套的 .flatMap 调用来说是句法确定的。您也可以明确地编写它(这不完全是 for-comprehension 的脱糖,但在功能上是等效的):

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