Rx vs Coroutines: Complex network chains on Android

karntrehan
Jul 27, 2019 · 4 min read

The title of this post may trigger a debate about Rx and coroutines being completely different solutions and hence incomparable. That is completely true: Rx works with asynchronous streams of data and coroutines are (in my opinion) asynchronous callback-driven functions. Yet, they are used interchangeably on Android to drive network calls and hence this comparative post.

Photo by Ishan @seefromthesky. Banner from canva.com

I had to work with a complex network chain for my Starwars sample Android app. I ended up writing the chain using both Rx and Coroutines. This post is about my experience with both.

The chain

I was using the SWAPI service to build the following chain:

draw.io

Considerations

As seen above, the failure of /planets/{id}/ adds some complexity to a fairly straightforward parallel chain.

The Rx Chain

Like a lot of you, Rx has been my go-to solution for asynchronous programming on Android for some time and is the first solution I tried to run this complex chain.

1. Get basic details

2(a). Get species & planets details from basic details

2(b). Get film details from basic details

3. Merge species, planets and film details to basic details and send to UI

full code here

The Coroutines Chain

This is my first complex experiment with Kotlin coroutines and may not be optimum. Coming from an Rx world, it was a bit tricky to get the coroutines to run in parallel and handle the failure of /planets/{id}/ at first.

1. Get basic details

2(a). Get species & planets details from basic details

2(b). Get film details from basic details

3. Merge species, planets and film details to basic details and send to UI

full code here

Observations

Both Rx and Coroutines worked well for the experiment. Following are my observations:

Source

All code images created with https://carbon.now.sh

MindOrks

Our community publishes stories worth reading on Android…