Networking in Android & Kotlin

Let’s play with Anko

Uddyami Agrawal
Kotlin Thursdays
4 min readApr 25, 2019

--

For those that might not know, this application had been inspired and started long ago from a true love story on Tinder of a dedicated Avocado giving Avocado facts for a year straight.

In the previous post, we had improved upon the existing application by updating the UI by fetching a random Avocado fact using AsyncTask. Before we run to start working with databases I wanted to check if the code is really KOTLIN material. And I was asking myself but with Kotlin around, why should I still use pure Java APIs? We explore that today with Anko. Anko is described on GitHub as “pleasant Android application development”. It’s all about making Android authentically Kotlin. It can almost make you love Android OS APIs (or maybe just not be mad at them). In this post, we will set up Anko doAsync like a pro!

References

  1. Antonio Leiva’s Using Anko to run background tasks with Kotlin in Android: https://antonioleiva.com/anko-background-kotlin-android/
  2. Anko Async.kt: https://github.com/Kotlin/anko/blob/38cada163c3ef0bfadc929cd3d68b436d5f10d51/anko/library/static/commons/src/main/java/Async.kt
  3. Future: https://developer.android.com/reference/java/util/concurrent/Future

Anko, explained

If vanilla Kotlin had you excited, then “Anko” will take it level 99. Code becomes very readable and concise. Not deviating too much, let’s look at AsyncTask Anko style.

There is a lot of decision-making that is needed before even starting any actual code. Check out “Anko” structure with all the syntax removed. The following is empty Async Task syntax. No steps involved, just two blocks with clear thread understanding.

doAsync is all that is required to ask the OS to run the following block in a separate thread, while uiThread brings our result back to our Main thread.

It only took me couple of minutes to make all changes from AsyncTask to doAsync {...}. The code is super clear and with WeakReference support added, it ensures call the to uiThread block runs for Activity or Fragment that is actually alive and not keep track of dead UI. I would love to hear how long it took for you guys to convert your AsyncTask!

You can see the complete Github repo here:

Anko helps use true KOTLIN constructs from ground up and is supported by JetBrains and Google. This is the new support library we cannot live without. I would recommend to check this huge library out. There are numerous nuggets out there to found.

We’ve set up our Async Task in Anko we will try and hit an actual api to retrieve our fact , See you next week!

But for all my Curious Georges’ out there .. what’s underneath the hood

It looks so nice! How did Anko achieve it?

From the Async.kt class itself:

Mind. Blown.

Let’s break this code down a little bit.

Anko devs rewrote the async API from scratch — loopers and everything! Let’s do quick recap for the asynchronous task operation API. The most low level OS API we have is called Future (doc). Future is like result holder of an asynchronous computation which will come back at some point later in time. Generally it is running on a different thread and some limited functionality to communicate with it. This lead to two new concepts called callable (doc) and promise (doc). We can use a metaphor to understand the two — if a company is callable they give you a number to call, generally no arguments are passed in but just call(). While promise is more human words like.. I promise you I will do this but I may error. promise at least comes with one assurance that it will have some response on your request. Next in line for ASYNC concepts is Runnable, it will only run the block and doesn’t have capability to return anything. We can configure which thread it needs to run and it will run on it.

These api’s are all from OS to help do ASYNC tasks.

doAsync returns a Future<Unit>. Futures are […]. According to Kotlin documentation -

The idea behind futures or promises (there are also other terms these can be referred to depending on language/platform), is that when we make a call, we’re promised that at some point it will return with an object called a Promise, which can then be operated on.

One place we all might be using these concepts already is Retrofit. Since it be OnPostExecute or uiThread they both are callback blocks that are called after the background work has returned it result. It is this reason that we keep track who called me or who was I promised ? To cancel or stop listening for response we make this reference to be nulled anytime aka always only keep WeakReference. Android OS has made this data object exclusively to allow garbage collector to collect an object even when someone is trying to keep track of it.

This explanation was over simplified. I would highly recommend reading actual docs for technical details. See you next time!

Navigate Networking in Android here:

--

--

Uddyami Agrawal
Kotlin Thursdays

female developer, tech enthusiast, but that’s not all