kotlinkotlinx.coroutinesanko

correct way of using coroutines in kotlin 1.3


I started using corotuines when it was still in experimental. With anko, I had something like

async(UI) {
    val request = bg { sendRequest() }
    val result = request.await()
    // UI work
}

I really like how it is structured and it does provide cleaner code vs callback hell imo. I just realized coroutines is now in stable channel and couldn't wait to try it out. I updated my kotlin and anko and now I have this

doAsync {
    val result = sendRequest()
    uiThread {
        // ui work
    }
}

Am I doing it correctly? This structure seems ugly to me. Although it might be more readable but I still like the old way of calling await(). Or maybe I miss something here? I remember one of the selling points when coroutines was introduced is less curly braces.


Solution

  • You don't need Anko to get good code with coroutines. Also, you don't need async and in fact you should avoid it for cases like yours, where you just want to make a non-blocking call and don't want to launch several such calls concurrently. Your basic idiom should be

    myScope.launch {
        val result = sendRequest()
        // UI work
    }
    

    where sendRequest() is

    suspend fun sendRequest() = withContext(Dispatchers.IO) { ... body ... }
    

    If you are calling this from an Android Activity, then myScope can be just the implicit this, and your activity must implement CoroutineScope:

    class MyActivity : AppCompatActivity, CoroutineScope {
        override val coroutineContext = SupervisorJob() + Dispatchers.Main
        ...
    }
    

    To get more insights, Explicit Concurrency by Roman Elizarov is highly recommended reading.