Rx java chaining .exists, .filter

java

#1

I have a Map<String, long>. I am using “exists” to find if the key is in Couchbase. It returns a Observable. I want to filter out the keys that are in Couchbase and return only keys that were in Couchbase.

How do I return the the keys ?

   .flatMap(new Func1<Entry<String,Long>, Observable<Boolean>>() {
                                       @Override
                                           public Observable<Boolean> call(Entry<String, Long> entry) {
                                                return bucket
                                               .async()
                                               .exists(entry.getKey());
                                          }
                                    })
                                    .filter(new Func1<Boolean, Boolean>() {
                                        @Override
                                        public Boolean call(Boolean t) {                                
                                            return t;
                                        }
                                    })

#2

If you are really only interested in collecting the keys that have a corresponding document in Couchbase, you need a nested flatMap:

Observable.from(myMap.entrySet())
    .flatMap(entry -> bucket.async()
        .exists(entry.getKey())
        .flatMap(exists -> exists ? Observable.just(entry.getKey()) : Observable.empty())
    );

However, if you need to do a get and use the content of the document down the chain, then you can make a shortcut by knowing that get returns an empty Observable if the document doesn’t exist. This avoids the exists and its boolean return value, but adds the overhead of fetching the documents:

Observable.from(myMap.entrySet())
    .flatMap(entry -> bucket.async().get(entry.getKey()))
    //do something else with the content of the documents that exist
;

#3

I tried the same with Java 7.Thanks.