Updated 16 April 2018
Coroutine are light-weight threads. A light weight thread means it doesn’t map on native thread, so it doesn’t require context switching on processor, so they are faster. Coroutines is a new way of writing asynchronous, non-blocking code in kotlin.
These are the functions to start the coroutine:
1. launch{}
2. async{}
The difference is that the launch{} does not return anything and the async{} returns an instance of Deferred<T>, which has an await function that returns the result of the coroutine like we have future in Java. and we do future.get() in Java to the get the result.
1 2 3 4 5 6 7 8 |
fun main(args: Array<String>) { launch { // launch new coroutine in background and continue delay(1000L) // non-blocking delay for 1 second (default time unit is ms) println("World!") // print after delay } println("Hello,") // main thread continues while coroutine is delayed Thread.sleep(2000L) // block main thread for 2 seconds to keep JVM alive } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// Parallel execution private fun taskA() { val one = async(CommonPool) { taskB() } val two = async(CommonPool) { taskC() } launch(CommonPool) { val combined = one.await() + "-->" + two.await() println("Combined : " + combined) } } // The output is // Combined : taskB-->taskC |
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.