Chaining and Running Retrofit calls in parallel with RxJava

Aung Thiha
3 min readNov 17, 2018

--

Beauty of my hometown, Mandalay

I’ve been playing around with RxJava for the past few days and I find it really enjoyable and really useful.

In my quest to fight my FOMO, I tried chaining a retrofit call with another two calls that are zipped together and run in parallel in two different threads and finally load the results into UI only when all of them are done. It’s like a magic. It feels amazing. Then, I immediately had an urge to share this amazing thing that I just learned. So, here I am writing a post.

I will write what I’ve learned in a series.

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

Before I dive into it, let me friendly inform you that this is my first post and this is merely what I’ve learned in the past few days as a brand new user of RxJava rather than an experienced one. So, if you find some mistakes or know better approach, please kindly point me out and it would be appreciated.

Furthermore, please be advised that this post assumes you’re already familiar with Dagger 2 and MVP design pattern.

Now, let’s dive into it. Imagine you have three api calls that go something like this in sequence

  1. Find current promotion from a promotion list
  2. Get a list of items that are promoted in current promotion
  3. Get a list of ads in current promotion

You can see that 2 and 3 don’t need to be run sequentially. They can be run in parallel when 1 is done so that the results can be loaded into UI faster. RxJava makes it easy to achieve this.

Let’s write our Retrofit interface first

Now, it’s turn for our Repository class

Although we’re not doing anything useful in the Repository class at this stage, we will in my next post. For now, PromotionRepository is added just to check on which thread the api calls will run. We also need a little help from map operator to do it. (If you know a better way to check threads, please point me out 🙂)

Finally, we can write our Presenter class.

Now, let’s run our app to see if we’re successfully running Retrofit calls as we desire.

D/RxJavaThread: fetchPromotions: RxCachedThreadScheduler-1
D/RxJavaThread: fetchSales: RxCachedThreadScheduler-1
D/RxJavaThread: fetchAds: RxNewThreadScheduler-1

Woo Hoo! “fetchSales” and “fetchAds” happen only after “fetchPromotions” and they run in two different threads in parallel.

I hope my post is helpful to others. If you enjoy my post, please give it some claps.

More posts coming soon….. ✍️

--

--

Aung Thiha

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