Skip to content

Instantly share code, notes, and snippets.

@GauravChaddha1996
Created January 30, 2021 18:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GauravChaddha1996/78b2163412a67a327cfdd08b92ac9fc9 to your computer and use it in GitHub Desktop.
Save GauravChaddha1996/78b2163412a67a327cfdd08b92ac9fc9 to your computer and use it in GitHub Desktop.
fun taskT(): Job {
return GlobalScope.launch(Dispatchers.IO) {
println("Starting C on ${Thread.currentThread().name}\n")
val resultT1 = t1()
println("Starting task T2,T3 on ${Thread.currentThread().name}")
val jobT2T3 = async {
val resultT2 = t2(resultT1)
val resultT3 = t3(resultT2)
return@async resultT3
}
/*
* Since task T4, T5 aren't dependant on task T2 or T3 using async
* for T2,T3 is a win for us since we can continue our execution.
* Task 'T4' output is input to task 'T5'.
*
* Builder explanation: async is used as we need result from these
* two tasks for our final result
* Task name: T4, T5
* Coroutine name: C4, C5 respectively
* Thread pool: Since T4 is a file read and T5 we database write operation,
* we use default thread pool for our combined coroutine
* suspension: It won't suspend the calling function.
* start context item : To demonstrate start keyword, we pass it as lazy
* - meaning only start this async coroutine when await() is called.
*
* */
println("Starting task T4,T5 on ${Thread.currentThread().name}\n")
val jobT4T5 = async(Dispatchers.Default, start = CoroutineStart.LAZY) {
println("Inside Task T4,T5 on ${Thread.currentThread().name}")
val resultT4 = t4()
val resultT5 = t5(scope = this, param4 = resultT4)
return@async resultT5
}
// omitted code here
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment