Skip to content

Instantly share code, notes, and snippets.

@GauravChaddha1996
Created January 30, 2021 18:15
Show Gist options
  • Save GauravChaddha1996/02160ddc1455551517790655a7324f23 to your computer and use it in GitHub Desktop.
Save GauravChaddha1996/02160ddc1455551517790655a7324f23 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
}
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
}
// delay so that task T2,T3 starts and T4,T5 doesn't,
// to demonstrate use of CoroutineStart.
delay(100)
println("Going to await result of task T2,T3 and T4,T5")
// Now we await the result of task T2,T3 and T4,T5
// and then combine their result.
// await() is a suspend function which either
// suspends the execution of calling function
// if the deferred doesn't hold the value or
// will return the result instantly.
// Suspension: Will suspend the calling coroutine
//
// Note: Here it may so happen that jobT2T3 await
// gives the result back and then we call await on
// jopT4T5 and it'll return the result immediately
// since it already computed it while t2 and t3 were executing.
// This is an example where calling a suspend function doesn't
// result in a suspension even though we were launching coroutines
// inside it because the result was already calculated
// by the time await was called.
val combinedResult = jobT2T3.await() + "_" + jobT4T5.await()
// After the await() calls for both tasks are done,
// the jobs are now in the completed state.
println("\nThe final result is $combinedResult")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment