[英]FS2 Running streams in sequence
我有一個相當簡單的用例。 我有兩個Web服務調用,一個獲取產品,另一個獲取關系。 我想運行fetchProducts()首先從產品集中提取一個字段,然后將輸出傳遞給fetchRelationships(ids:Seq [String]),以便可以在產品上重新設置關系。 這是代碼:
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來表達它,或者我是否應該使用它。
不幸的是,您在問題中編寫的代碼與您的文本描述不匹配,並且錯過了很多重要的內容(例如整個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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.