Friday, August 28, 2015

Couchbase Java SDK with Rx-Java

A neat thing about Couchbase Java SDK is that it is built on top of the excellent Rx-Java library, this enables a reactive way to interact with a Couchbase server instance which is very intuitive once you get the hang of it.

Consider a very simple json document that I intend to store in Couchbase:


and a Java class to hold this json:

public class KeyVal {
    private String key;
    private String value;


The following is the code to insert an instance of KeyVal to a Couchbase bucket:

JsonObject jsonObject = JsonObject.empty().put("key", keyVal.getKey()).put("value", keyVal.getValue());
JsonDocument doc = JsonDocument.create(keyVal.getKey(), jsonObject);
Observable<JsonDocument> obs = bucket

The return type of the insert is an Observable, so if I needed to map the return type back a KeyVal I can use the extensive mapping support provided by Observable class.

Observable<KeyVal> obs = bucket
                .map(jsonDoc -> 
                    new KeyVal(, jsonDoc.content().getString("value"))

Other API's follow a similar pattern, for eg. to retrieve the saved document:

                .map(doc ->
                        new KeyVal(,

If you are interested in exploring this sample further, here is my github repo with a working example -


No comments:

Post a Comment