我有一个相当简单的用例。我有两个web服务调用,一个是获取产品,另一个是获取关系。我希望运行fetchProducts(),首先从产品集中提取一个字段,然后将输出传递给fetchRelationships(id: SeqString),这样我就可以将关系设置回产品上。下面是代码:
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来表达这个问题,或者我是否应该使用它。
发布于 2018-01-11 01:01:25
不幸的是,您在问题中的代码与您的文本描述不匹配,并且遗漏了相当多的重要部分(例如整个Relationship类)。也不清楚是什么
我受到外部Api的限制,无法分批获得结果。
真的意味着。此外,还不清楚为什么Product中的所有字段(包括productId )都是Option。
下面的代码编译并且可能是您需要的代码,也可能不是您需要的代码:
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
}https://stackoverflow.com/questions/48197375
复制相似问题