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 {
    Single getMe();

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

    .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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s