Anupam Singh
Sep 4, 2018 · 3 min read
Does the image reminds you of your last multithreaded code?

Have you ever wished that your Multithreading code is never read by someone who has your address and a knife?

Kotlin Coroutines are here to help you with the nightmares. In this episode with Shashank Kumar from Urbanclap, we talk about how we can leverage Coroutines in our day to day development and make our multithreaded code easier to understand.

Show Notes

Kotlin: Statically typed programming language that runs on the Java virtual machine.

Coroutines : General control structure whereby flow control is cooperatively passed between two different routines without returning.

Kotlin Coroutines : Stack-less light weight threads managed by users which help in writing asynchronous, non blocking code.

Kotlin Coroutines works on Continuation programming paradigm

Components of Kotlin Coroutine

CoroutineDispatcher : Determines what thread or threads the corresponding coroutine uses for its execution, it can confine coroutine execution to a specific thread, dispatch it to a thread pool, or let it run unconfined.

Job : A cancellable task with a simple life-cycle . Job can be arranged into parent-child hierarchies where cancellation or completion of parent immediately cancels all its children.

Launch Types : Builder functions which define execution time of a job. Immediate launch or a async launch is possible, further customisation can be done through multiple CoroutineStart types.

Executable Block : Code block which you pass to execute your task.

In the episode we also talk about run blocking, how different launch types works and how can we leverage various operators in Kotlin Coroutines.

Further deep dive into internal api's of Kotlin Coroutines can be done here and here.


Task : Make two independent function calls and print their result only after both of them have executed.

Solution 1 :

fun main(args: Array<String>) {
val one = runFunctionFor2Seconds()
val two = runFunctionFor4Seconds()
println("One : $one")
println("Two : $two")
}
fun runFunctionFor2Seconds(): String {
Thread.sleep(2000)
return "2s missisipi work"
}
fun runFunctionFor4Seconds(): String {
Thread.sleep(3000)
return "4s missisipi work"
}

Incorrect : As main wont wait for results from doWorkFor1Seconds() and doWorkFor2Seconds() program will run sequentially.

Now can we solve the task using Kotlin Coroutines ?

Solution 2 : Using runBlocking .

fun main(args: Array<String>) {
runBlocking {
val one = runFunctionFor2Seconds()
val two = runFunctionFor4Seconds()
println("One : $one")
println("Two : $two")
}
}
suspend fun runFunctionFor2Seconds(): String {
delay(2000)
return "2s missisipi work"
}
suspend fun runFunctionFor4Seconds(): String {
delay(4000)
return "4s missisipi work"
}

Incorrect : As runBlocking runs new coroutine and blocks current thread interruptibly until its completion, this is equivalent to calling Thread.sleep() as in solution 1, and the program will run sequentially

Solution 3 : Using launch .

fun main(args: Array<String>) {
launch {
val one = runFunctionFor2Seconds()
val two = runFunctionFor4Seconds()
println("One : $one")
println("Two : $two")
}
//Main won't wait for result
}
suspend fun runFunctionFor2Seconds(): String {
delay(2000)
return "2s missisipi work"
}
suspend fun runFunctionFor4Seconds(): String {
delay(4000)
return "4s missisipi work"
}

Incorrect : Here doWorkFor1Seconds and doWorkFor2Seconds would run in sync but the whole launch block would run in async and main won’t wait for its completion.

Solution 4: Using combination of runBlocking and async

fun main(args: Array<String>) {
val job1 = async {
runFunctionFor2Seconds()
}
val job2 = async {
runFunctionFor2Seconds()
}
runBlocking {
println(job1.await() + " " + job2.await())
}
//Main would wait for result
}
suspend fun runFunctionFor2Seconds(): String {
delay(2000)
return "2s missisipi work"
}
suspend fun runFunctionFor4Seconds(): String {
delay(4000)
return "4s missisipi work"
}

Correct : Here doWorkFor1Seconds and doWorkFor2Seconds would run in async but calling thread would wait for result since await is called on runBlocking


In this episode we tried to introduce Kotlin Coroutines as currently its in experimental and as it matures to stable we will release episodes deepdiving into its components.

You can also contribute to the Kotlin Coroutines project here .

You may follow our Subject Matter Experts on these platforms:

Shashank Kumar : Github, Twitter, linkedin

Follow us on twitter for regular udpates and feel free to DM the hosts (Anupam & Tushar) for any queries.

AndroIDIOTS

An android developer publication to stay updated with whats new in android, best practices and how to become a better android developer

Thanks to Tushar Gupta

Anupam Singh

Written by

1/2 of AndroIDIOTS.in

AndroIDIOTS

An android developer publication to stay updated with whats new in android, best practices and how to become a better android developer

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade