我有一段调用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为true(存在于数据库中),4、5、6为false(意味着不存在于数据库中)。我成功地使用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
}
}
有没有不需要中间映射(不需要填充中间数据结构,而只是通过操作流来完成)的方法呢?看起来不太干净啊!!谢谢。