12

I just started learning Kotlin coroutines and was trying to simulate some long time API-calls with showing the result on the UI:

class MainActivity : AppCompatActivity() {
    fun log(msg: String) = println("[${Thread.currentThread().name}] $msg")

    override
    fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        this.setContentView(R.layout.activity_main)
        val resultTV = findViewById(R.id.text) as TextView

        val a = async(CommonPool) {
            delay(1_000L)
            6
        }

        val b = async(CommonPool) {
            delay(1_000L)
            7
        }

        launch(< NEED UI thread here >) {
            val aVal = a.await()
            val bVal = b.await()
            resultTV.setText((aVal * bVal).toString())
        }
    }
}

I don't understand how could I possibly use launch method with main context.

Unfortunately, I was not able to find anything about delivering results for some specific threads on the official tutorial for coroutines.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
Rostyslav Roshak
  • 3,859
  • 2
  • 35
  • 56

6 Answers6

10

Edit:

Also see an official example in Kotlin repo

you need to implement Continuation interface which makes a callback onto Android UI thread and Coroutine context

e.g. (from here)

private class AndroidContinuation<T>(val cont: Continuation<T>) : Continuation<T> by cont {
    override fun resume(value: T) {
        if (Looper.myLooper() == Looper.getMainLooper()) cont.resume(value)
        else Handler(Looper.getMainLooper()).post { cont.resume(value) }
    }
    override fun resumeWithException(exception: Throwable) {
        if (Looper.myLooper() == Looper.getMainLooper()) cont.resumeWithException(exception)
        else Handler(Looper.getMainLooper()).post { cont.resumeWithException(exception) }
    }
}

object Android : AbstractCoroutineContextElement(ContinuationInterceptor), ContinuationInterceptor {
    override fun <T> interceptContinuation(continuation: Continuation<T>): Continuation<T> =
        AndroidContinuation(continuation)
}

Then try:

launch(Android) {
    val aVal = a.await()
    val bVal = b.await()
    resultTV.setText((aVal * bVal).toString()) 
}

more info:

https://medium.com/@macastiblancot/android-coroutines-getting-rid-of-runonuithread-and-callbacks-cleaner-thread-handling-and-more-234c0a9bd8eb#.r2buf5e6h

pt2121
  • 11,720
  • 8
  • 52
  • 69
  • Please refer to the official library for android coroutines -> https://github.com/gildor/kotlin-coroutines-android/blob/master/coroutines-android/README.md – Robert Estivill Jun 20 '17 at 12:29
  • Is it from JetBrains or Android team? What do u mean by official? – pt2121 Jun 20 '17 at 12:32
9

You shall replace < NEED UI thread here > in your code with UI context from kotlinx-coroutines-android module of kotlinx.coroutines project. Its usage is explained in the Guide to UI programming with coroutines with quite a few examples.

Roman Elizarov
  • 27,053
  • 12
  • 64
  • 60
4

First of all include right library designed for Android

build.gradle

apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

android{
...
   dependencies{
      ...
      implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:0.19.3"

   }

  kotlin {
    experimental {
        coroutines "enable"
    }
  }
}

Then you are free to use UI

suspend private fun getFilteredGList(enumList: List<EnumXXX>) = mList.filter {
    ...
}

private fun filter() {
    val enumList = listOf(EnumX1, EnumX2)
    launch(UI){
        val filteredList = getFilteredList(enumList)
        setMarkersOnMap(filteredList)
    }

}

For those that expose project using kotlin experimental in gradle as .aar or .apk to other projects module - Just remember, when You're using kotlin experimental parent modules/project have to accept kotlin experimental as well

kotlin {
    experimental {
        coroutines "enable"
    }
  }
murt
  • 3,790
  • 4
  • 37
  • 48
2

There are a couple of useful tools that can be used for the purpose of long time running API-calls in Activity/Fragment. So basically if you want to run two long running tasks in parallel and update UI after both are finished you can do it the next way:

lifecycleScope.launch {
    // launching two tasks in parallel
    val aValDeferred = executeLongRunningTask1Async()
    val bValDeferred = executeLongRunningTask2Async()

    // wait for both of them are finished
    val aVal = aValDeferred.await()
    val bVal = bValDeferred.await()

    // update UI
    resultTV.setText((aVal * bVal).toString())
}

private fun executeLongRunningTask1Async(): Deferred<Int> = lifecycleScope.async(Dispatchers.Default) {
    delay(1_000L)
    6
}

private fun executeLongRunningTask2Async(): Deferred<Int> = lifecycleScope.async(Dispatchers.Default) {
    delay(1_000L)
    7
}

lifecycleScope - is a CoroutineScope, by default it has Dispatchers.Main context, it means we can update UI in the launch block. For LifecycleScope, use androidx.lifecycle:lifecycle-runtime-ktx:2.4.0 or higher.

lifecycleScope.async(Dispatchers.Default) - here Dispatchers.Default is used as a context of the coroutine to have the async block running in the background thread.

Sergio
  • 27,326
  • 8
  • 128
  • 149
0

Anko has a wrapper to do it very simply-- see: https://github.com/Kotlin/anko/wiki/Anko-Coroutines

private fun doCallAsync() = async(UI) {

    val user = bg { getUser() }
    val name = user.await().name
    val nameView = findViewById(R.id.name) as TextView

    nameView.text = name;

}
nAndroid
  • 862
  • 1
  • 10
  • 25
0

This answer may be 2.5yrs after the OP's question but it may still help out others in a similar situation.

The original goal can be achieved in a far simpler way than the accepted answer above without the use of async/await (statements 1, 2 and 3 will be executed in sequence, with their associated delays behaving as expected):

override fun onCreate(savedInstanceState: Bundle?) {
    :
    :
    :
    :
    GlobalScope.launch(Dispatchers.Main) {

    val aVal = a()   // statement 1
    val bVal = b()   // statement 2

    resultTV.setText((aVal * bVal).toString())    // statement 3
    }
    :
    :
}

suspend fun a(): Int {
    delay(1_000L)
    return 6
}

suspend fun b(): Int {
    delay(1_000L)
    return 7
}
Oke Uwechue
  • 314
  • 4
  • 14