RxJava2 Completable Example

When using RxJava to listen to events, especially API responses from Retrofit, we typically use the Observable class. Similarly to using a Single, we don’t always need the onNext.

In fact, sometimes we don’t need any return info example for the complete event. For example, if we are posting a task to an API and we just want to know that the request was successful. For these casses we can use the Completable class.

Say we have this retrofit interface:

public interface APIClient {
    @POST("/task")
    Completable createTask(@Body String taskName);
}

Then we can simply use a Completable to let us know if the request was successful.

apiClient.createTask("a new task")
    .subscribe(() -> {
        // handle complete
    }, throwable -> {
        // handle error
    });

As with a Single, this helps us save a bit of boilerplate code throughout our code base.

RxJava2 Single Example

When using RxJava to listen to events, especially API responses from Retrofit, we typically use the Observable class. However, sometimes we don’t need the onNext call because we simply want the final result. For that, we can use a Single.

Say we have this retrofit interface:

public interface APIClient {
    @GET("/me")
    Single getMe();
}

Then we can simply use a Single to let us know when the user is fetched.

apiClient.getMe()
    .subscribe(user -> {
        // user returned
    }, throwable -> {
        // handle error
    });

It’s not a huge difference, but when you are repeating this code over a code base it can help to remove that extra function. It also makes the code more readable with the intent being to only handle the returned data.