我有一个代码,它调用 couchbase 来获取一些行,如下所示:
val gotValues: Observable[JsonDocument] = Observable.from(rowKeys).flatMap(id =>
couchbaseBucket.async().get(id))
如果我有 1,2,3,4,5,6 作为输入行键并且数据库中只存在第 1,2,3 行,那么 observable 只会收到大约 1,2,3 的通知。
然而,我的要求是我返回一个 1、2、3 为真(存在于数据库中)和 4、5、6 为假的地图(意味着数据库中不存在)。我设法用 scala observable 做到了这一点,但是我使用中间地图数据结构来返回包含所有 id 的总地图。下面是一个模拟我的问题的示例代码..
object Main extends App {
import rx.lang.scala.Observable
val idsToFetch = Seq(1,2,3,4,5,6)
println(isInDBOrNot()) // {1=true, 2=true, 3=true, 4=false, 5=false, 6=false}
private def isInDBOrNot(): ConcurrentHashMap[Int, Boolean] = {
val inAndNotInDB = new java.util.concurrent.ConcurrentHashMap[Int, Boolean]
// - How can I avoid the additional data structure?
// - In this case a map, so that the function will return
// a map with all numbers and for each if exist in DB?
// - I mean I want the function to return a map I don't
// want to populate that map inside the observer,
// it's like a mini side effect I would rather simply
// manipulate the stream.
Observable.from(idsToFetch)
.filterNot(x => x == 4 || x == 5 || x == 6) // Simulate fetch from DB, 4,5,6 do not exist in DB, so not returned.
.subscribe(
x => inAndNotInDB.put(x, true),
e => println(e),
() => idsToFetch.filterNot(inAndNotInDB.containsKey)
.foreach(inAndNotInDB.put(_, false)) // mark all non-found as false.
)
inAndNotInDB
}
}
无论如何要在没有中间映射的情况下做到这一点(不填充中间数据结构,但只能通过操纵流)?看起来不干净!!. 谢谢。