首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >FS2按顺序运行流

FS2按顺序运行流
EN

Stack Overflow用户
提问于 2018-01-10 22:50:16
回答 1查看 839关注 0票数 0

我有一个相当简单的用例。我有两个web服务调用,一个是获取产品,另一个是获取关系。我希望运行fetchProducts(),首先从产品集中提取一个字段,然后将输出传递给fetchRelationships(id: SeqString),这样我就可以将关系设置回产品上。下面是代码:

代码语言:javascript
复制
def fetchProducts(): Stream[IO, Seq[Product]]= {
 //webservice call
}

def fetchRelationship(ids: Seq[Product]): Stream[IO, Seq[Relationship]] = {
 //webservice call
}

//Pseudocode. How can I do this with fs2 Streams?
def process = {
      val prods = fetchProducts() //run this first
      val prodIds = prods.flatMap(i => i.productId)
      val rels = fetchRelationships(prodIds) //run after all all products are fetched 
      prods.forEach(p => p.setRelation(rels.get(p.id))
    }
}

 case class Product(productId: Option[String],
                        name: Option[String],
                        description: Option[String],
                        brandName: Option[String])

我受到外部Api的限制,无法分批获得结果。因此,我不知道如何用fs2来表达这个问题,或者我是否应该使用它。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-01-11 01:01:25

不幸的是,您在问题中的代码与您的文本描述不匹配,并且遗漏了相当多的重要部分(例如整个Relationship类)。也不清楚是什么

我受到外部Api的限制,无法分批获得结果。

真的意味着。此外,还不清楚为什么Product中的所有字段(包括productId )都是Option

下面的代码编译并且可能是您需要的代码,也可能不是您需要的代码:

代码语言:javascript
复制
case class Product(productId: Option[String],
                   name: Option[String],
                   description: Option[String],
                   brandName: Option[String],
                   relationships: mutable.ListBuffer[Relationship]) {

}

case class Relationship(productId: String, someInfo: String)

def fetchProducts(): Stream[IO, Seq[Product]] = {
  //webservice call
  ???
}

//    def fetchRelationships(ids: Seq[Product]): Stream[IO, Seq[Relationship]] = {
def fetchRelationships(ids: Seq[String]): Stream[IO, Seq[Relationship]] = {
  //webservice call
  ???
}

def process():  = {
  val prods = fetchProducts() //run this first
  val prodsAndRels: Stream[IO, (Seq[Product], Seq[Relationship])] = prods.flatMap(ps => fetchRelationships(ps.map(p => p.productId.get)).map(rs => (ps, rs)))

  val prodsWithFilledRels: Stream[IO, immutable.Seq[Product]] = prodsAndRels.map({ case (ps, rs) => {
    val productsMap = ps.map(p => (p.productId.get, p)).toMap
    rs.foreach(rel => productsMap(rel.productId).relationships += rel)
    ps.toList
  }
  })
  prodsWithFilledRels
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48197375

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档