RxJava Observe a missing document

Hello,

I want to check wether a document exists asynchronously, but I can’t find how to get notified of missing documents:

bucket.async().get("THIS_DOC_DOES_NOT_EXIST")
                       .subscribe(new Observer<JsonDocument>() {
			    @Override
			    public void onCompleted() {
			    	LOG.info("Observable done!");
			    }
			
			    @Override
			    public void onError(Throwable e) {
			    	LOG.error("Something happened");
			        e.printStackTrace();
			    }
			
			    @Override
			    public void onNext(JsonDocument doc) {
			    	LOG.info("Got: " + doc.id());
			    }
			});

I would expect onError() to be called, or maybe onNext(null), but it seems it’s not the case. Am I doing something wrong ?

OK I found a relevant piece of information:

com.couchbase.client.java.AsyncBucket.get(String id)
Retrieves a JsonDocument by its unique ID. If the document is found, a JsonDocument is returned. If the document is not found, the Observable completes without an item emitted

So what’s the way to check if a document exists?

A simple way would be to chain in the “singleOrDefault()” operator with something like “singleOrDefault(null)”. You can then check in your onNext call if the document is null (then it’s not found) and if it’s non null it was found.

Note that, from a global Rx perspective, there is also the alternative of using defaultIfEmpty which is a little bit simpler (allows the original to emit n items, whereas singleOrDefault additionally checks that no more than one item is ever emitted).

But in our case we only ever expect the get to return one document, so singleOrDefault is the best match.

1 Like

Thank you, defaultIfEmpty was indeed what I was looking for.

2 Likes