Skip to content

Instantly share code, notes, and snippets.

View GauravChaddha1996's full-sized avatar
🙂
Giving my best!

Gaurav Chaddha GauravChaddha1996

🙂
Giving my best!
View GitHub Profile
runBlocking {
val scope = CoroutineScope(Dispatchers.IO)
val j = scope.launch {
println("Inside parent job")
delay(50)
val p = launch {
println("Inside child job")
// Notice how we check that the job's isActive
while (true && isActive) {
print(0)
runBlocking {
val scope = CoroutineScope(Dispatchers.IO)
val j = scope.launch {
println("Inside parent job")
delay(50)
val p = launch {
println("Inside child job")
while (true) {
print(0)
}
runBlocking {
val scope = CoroutineScope(Dispatchers.IO)
val j = scope.launch {
println("Inside parent job")
delay(50)
val p = launch {
println("Inside child job")
delay(500)
println("Ending of child job")
}
runBlocking {
val scope = CoroutineScope(Dispatchers.IO)
val j = scope.launch {
println("Inside parent job")
delay(50)
val p = launch {
println("Inside child job")
delay(500)
println("Ending of child job")
}
runBlocking {
val scope = CoroutineScope(Dispatchers.IO)
val j = scope.launch {
println("Inside parent job")
delay(50)
val p = launch {
println("Inside child job")
delay(500)
println("Ending of child job")
}
class MyFragment: Fragment() {
override fun onViewCreated(view: View, state: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewLifecycleOwner.lifecycleScope.launch {
// do-some ui work
}
}
init {
fun main() {
// Thread: Main
// Builder explanation: runBlocking is used for bridging coroutine
// code to normal code.
// It blocks the thread calling it until it's execution is complete.
// We call our taskT() on main thread and launch coroutines inside it.
// It returns the coroutine job as result.
runBlocking {
val parentCoroutineC = taskT()
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 {
println("Inside Task T2,T3 on ${Thread.currentThread().name}")
// t2 and t3 are suspend functions and will suspend this block until it returns the result
val resultT2 = t2(resultT1)
val resultT3 = t3(resultT2)
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
}
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
}