Kotlin x Anko (Part 3)
Hi folks! back again to my story, and this is the last part of my story telling about Anko as one of the most famous helper library in Kotlin (especially for Android 😃)… if you need to read my previous story, you can check on this link.
Right now, I’ll tell you a short background on Kotlin Coroutines. Based on Kotlin official documentation…
Coroutines provide a way to avoid blocking a thread and replace it with a cheaper and more controllable operation: suspension of a coroutine
and…
Coroutines simplify asynchronous programming by putting the complications into libraries. The logic of the program can be expressed sequentially in a coroutine, and the underlying library will figure out the asynchrony for us
In my humble opinion (IMHO) Coroutines for me is a new way of how to define a threading logic without blocking any thread 👍
In this part, I’ll show you how to implement a coroutines in Android by using Anko dependencies, instead of doing a manual way… because Anko also provide some wrapper that we need to implement this things 😃… First thing first, we need to add some dependencies there;
implementation 'org.jetbrains.anko:anko-coroutines:0.10.5'
If you’re using android SDK ≥ 25, you will need this;
implementation 'org.jetbrains.anko:anko-sdk25-coroutines:0.10.5'
Also, you can add more coroutines dependencies to bind into your view component by adding this;
implementation 'org.jetbrains.anko:anko-appcompat-v7-coroutines:0.10.5'
implementation 'org.jetbrains.anko:anko-recyclerview-v7-coroutines:0.10.5'
implementation 'org.jetbrains.anko:anko-design-coroutines:0.10.5'
Based on Anko official wiki, Coroutines listener helpers are define by two types;
- Listener as Reference
- Listener in Background
And… what is that ? Coroutines listener as reference are works in condition like this statement;
If your asynchronous API does not support cancellation, your coroutine may be suspended for an indefinite time period. As a coroutine holds the strong references to captured objects, capturing the instance of Activity or Fragment instance may cause a memory leak
I’ll give you some short example with my own code 😆…
val reference = this.asReference()
async(UI) {
val result = "Coroutines are cool!"
reference().showResult(result)
}
Apart from that, listener as background are based on it’s name only working in a background thread instead 😃. Like, if you’re doing some API call or querying some data in your local storage using SQLite (like I’m doing on my previous article). The following example are given some short detail explanation about the coroutines works on background thread…
async(UI) {
val result = bg {
"Welcome to Coroutines!"
}.await()
}
So, did you understand the difference between type of coroutines listener that provide on Anko library, right ? 😆
Ok, that’s all from my point of view about Anko library things. If you have any question… please don’t hesitate to contact me 😃 … or you can check all example from my github