-
Notifications
You must be signed in to change notification settings - Fork 23
Comparing coroutine vs suspend function
Devrath edited this page Jan 14, 2024
·
2 revisions
- Observe that both functions are running concurrently.
Coroutine-No:1 Working at index 0
Coroutine-No:2 Working at index 0
Coroutine-No:1 Working at index 1
Coroutine-No:2 Working at index 1
Coroutine-No:2 Working at index 2
Coroutine-No:1 Working at index 2
Coroutine-No:2 Working at index 3
Coroutine-No:1 Working at index 3
Coroutine-No:2 Working at index 4
Coroutine-No:1 Working at index 4
Coroutine-No:2 Working at index 5
Coroutine-No:1 Working at index 5
Coroutine-No:2 Working at index 6
Coroutine-No:1 Working at index 6
Coroutine-No:2 Working at index 7
Coroutine-No:1 Working at index 7
Coroutine-No:2 Working at index 8
Coroutine-No:1 Working at index 8
Coroutine-No:2 Working at index 9
Coroutine-No:2 completed
Coroutine-No:1 Working at index 9
Coroutine-No:1 completed
- Observe that both functions are running synchronously one after another.
Coroutine-No:1 Working at index 0
Coroutine-No:1 Working at index 1
Coroutine-No:1 Working at index 2
Coroutine-No:1 Working at index 3
Coroutine-No:1 Working at index 4
Coroutine-No:1 Working at index 5
Coroutine-No:1 Working at index 6
Coroutine-No:1 Working at index 7
Coroutine-No:1 Working at index 8
Coroutine-No:1 Working at index 9
Coroutine-No:1 completed
Coroutine-No:2 Working at index 0
Coroutine-No:2 Working at index 1
Coroutine-No:2 Working at index 2
Coroutine-No:2 Working at index 3
Coroutine-No:2 Working at index 4
Coroutine-No:2 Working at index 5
Coroutine-No:2 Working at index 6
Coroutine-No:2 Working at index 7
Coroutine-No:2 Working at index 8
Coroutine-No:2 Working at index 9
Coroutine-No:2 completed
class NonCancellableDemoVm @Inject constructor() : ViewModel() {
private var job: Job? = null
fun startTwoCoroutines() {
// Start a root coroutine
job = CoroutineScope(Dispatchers.IO).launch {
// Start a coroutine-1
launch {
coRoutineOne(1)
}
// Start a coroutine-2
launch {
coRoutineOne(2)
}
}
}
fun startTwoSuspendFunctions() {
// Start a coroutine
job = CoroutineScope(Dispatchers.IO).launch {
// Start a suspend function-1
coRoutineOne(1)
// Start a suspend function-2
coRoutineOne(2)
}
}
private suspend fun coRoutineOne(coroutineNo: Int) {
try {
repeat(10) { index ->
delay(500)
// Check if the coroutine has been canceled
if (!coroutineContext.isActive) {
println("Coroutine-No:$coroutineNo canceled at index $index")
} else {
// Continue with the main logic
println("Coroutine-No:$coroutineNo Working at index $index")
}
}
// Additional logic after the loop
println("Coroutine-No:$coroutineNo completed")
} catch (e: CancellationException) {
// Handle cancellation-specific tasks
println("Coroutine-No:$coroutineNo canceled")
}
}
fun cancel() {
job?.cancel()
}
}