Handling different status codes from Retrofit calls differently with RxJava

Aung Thiha
2 min readNov 25, 2018

--

Beauty of my hometown, Mandalay

Previously, I wrote about Chaining and Running Retrofit calls in parallel with RxJava. This post is kind of part 2 but you don’t really need to read that first to understand this but if you’re interested, please do check my previous post.

This is one of the posts from the series I’m writing.

  1. Chaining and Running Retrofit calls in parallel with RxJava
  2. Handling different status codes from Retrofit calls differently with RxJava (You’re here)
  3. Mocking JSON responses from Retrofit calls and make them Observable for unit testing

Previous, our PromotionService looks like this.

The problem with that approach is that we can’t get status code. Not only that, we can’t call any useful methods that come with the retrofit’s Response class. So, we need to wrap our response with Response class like so.

Now, we can check status codes in Repository class. Just for the purpose of demonstrating an example usage, we’re gonna check if the status code is 204 and return an empty Optional if it is. We need the Optional class because 204 has nothing to emit and RxJava doesn’t let us emit null. Plus, we don’t want our presenter to recognize empty responses as errors because we may want to show the users something like “no content available” and clearly having no content is not an error.

Don’t get frustrated over the fact that Android API lower than 24 doesn’t support Java 8 Optional. I have written a similar class based on it and it’s provided below.

Now, we can handle different status codes differently in our Repository class.

Finally, in our presenter, we can receive empty response as Optional object.

There we have it. Empty contents from Retrofit call is now nicely handled. As a bonus, I use onErrorResumeNext to continue showing sales even if fetching ads fails.

I hope the comments in the code explains well enough. Let me know if it’s still confusing, I’ll try my best to explain better.

If you like my post, please give it some claps.

Happy coding!

--

--

Aung Thiha

Android | Jetpack Compose | A/B Testing | TDD | CI/CD | SOLID | Clean Architecture | Design Patterns | Mentorship | Recruitment