Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace Anko's doAsync, uiThread with kotlin 1.1.0 kotlinx-coroutines-core lib's features?

Tags:

android

kotlin

i have some code like:

doAsync{
...
uiThread{
...
}
}

how can i replace doAsync and uiThread with something new from kotlinx-coroutines-core lib?

like image 458
egordeev Avatar asked Mar 06 '17 14:03

egordeev


People also ask

How do I add coroutines to Kotlin project?

Go to Tools → Kotlin → Configure Kotlin Plugin Updates, select “Stable” in the Update channel drop-down list, and then click Check for updates. We are adding coroutines-core along with coroutines-android. Now, sync your project with gradle files and you are ready use the latest Coroutines.

What is Kotlin coroutines example?

A coroutine is a concurrency design pattern that you can use on Android to simplify code that executes asynchronously. Coroutines were added to Kotlin in version 1.3 and are based on established concepts from other languages.

What is Anko Android?

The Anko library is an Android library written and maintained by JetBrains. Anko helps you to work faster and smarter when building Android apps. From what I've gathered, the above graphic is how the name Anko came about. Anko has four parts: Anko Commons.


2 Answers

coroutines library version 1.3.7:

GlobalScope.async(Dispatchers.Default) {
            // do background work
            withContext(Main) {
                // do ui work
            }
        }
like image 183
Sun Jiao Avatar answered Sep 28 '22 11:09

Sun Jiao


The exact replacement for the pseudocode in the question is

GlobalScope.launch(Dispatchers.Default) {  // replaces doAsync
    ...
    launch(Dispatchers.Main) { // replaces uiThread
        ...
    }
}
like image 37
x1a4 Avatar answered Sep 28 '22 10:09

x1a4