Viktor Kinko

Coroutines in Kotlin for easy agloritms' parallelism

Coroutines are alike threads: they set sequence of commands' execution with its own stack and variables. The main difference is that coroutines can delay its execution to wait for result of another coroutine.

What does it mean for Android developer? As any syntactic sugar - more readable code.
Viktor Kinko
Android Developer
It needs to notice that coroutines are not only syntactic sugar - because they're released by lightweight threads its creation takes less time that classic threads creation so they're more profitable in terms of performance in the system with high parallelism. But it's theoretically.
Practically I faced trivial task of code refactoring. Conditions of the problem:

- there is a Google Map on screen
- you have to display markers that match points on way
- points are set by text addresses
Difficulties and implementation:

- firstly initialize Google Map. You can do it by getMapAsync method in another thread
- you need to use Geocoder that executes internet request in particular thread to get geo coordinates of way points
- after you got a Map you can add markers if they're already gotten. It has to be done in main thread
As a result after logic extraction into separated class I faced such a code:
Let's write this code with coroutine:
The main advantage that we got by coroutines is modification easiness for parallelism.
Now execution (it's obvious in coroutine) is going by this chain:
getPoints -> getGoogleMap -> addRouteOnMap
But it's ineffective. We don't initialize map before we get points' coordinates. If it's poor connection we can wait till timeout.
On the other side, if we change function places and call getGoogleMap at first, it needs to wait map initializing, if the phone is weak, and then wait for request result.
The best way to organize this process is to launch two functions in parallel and transfer results to the third:
getPoints  ->  addRouteOnMap  ->  getGoogleMap
To organize this process in classic threads, that were in second example, we would add tread-safe flags of loading and at the end of each getPoints and getGoogleMap functions check if the parallel function complete. And only the moment both functions complete we can call addRouteOnMap.
For coroutine all is simple. We have to change only initMap:
It's sure that it's just a method for code and threads organization same as RX or calls' chain. Get this, how it's simple to change the way of execution and how simple you can read the code. If you implement this example in more complex algorithms you'll reach significant increasing productivity and improve user experience.
Thanks for reading!