Log.i("yang", "Main Start")
val mScope = CoroutineScope(Dispatchers.IO)
val mJob1 = mScope.launch {
try {
Log.i("yang", "Job1 Start")
delay(1000)
Log.i("yang", "Job1 End")
} catch (e: Exception) {
Log.i("yang", "Job1 Cancelled e = ${e.message}")
}
}
val mJob2 = mScope.launch {
try {
Log.i("yang", "Job2 Start")
delay(2000)
Log.i("yang", "Job2 End")
} catch (e: Exception) {
Log.i("yang", "Job2 Cancelled e = ${e.message}")
}
}
Log.e("yang", "Main Continue")
Thread.sleep(500)
mScope.cancel()
Log.e("yang", "Main Cancel")
Log.i("yang", "Main End")
// log
2025-01-06 17:36:52.588 1752-1752 yang com.example.myapplication I Main Start
2025-01-06 17:36:52.593 1752-1752 yang com.example.myapplication E Main Continue
2025-01-06 17:36:52.593 1752-2367 yang com.example.myapplication I Job1 Start
2025-01-06 17:36:52.594 1752-2391 yang com.example.myapplication I Job2 Start
2025-01-06 17:36:53.094 1752-1752 yang com.example.myapplication E Main Cancel
2025-01-06 17:36:53.094 1752-1752 yang com.example.myapplication I Main End
2025-01-06 17:36:53.094 1752-2367 yang com.example.myapplication I Job1 Cancelled e = Job was cancelled
2025-01-06 17:36:53.094 1752-2407 yang com.example.myapplication I Job2 Cancelled e = Job was cancelled
Log.i("yang", "Main Start")
var mJob = CoroutineScope(Dispatchers.IO).launch {
try {
Log.i("yang", "IO Start")
Thread.sleep(1000)
if (!isActive){
Log.i("yang", "IO is not active")
return@launch
}
Log.i("yang", "IO End")
} catch (e: Exception) {
Log.i("yang", "Launch Exception = ${e.message}")
}
}
Log.i("yang", "Main Continue")
Thread.sleep(500)
mJob.cancel()
Log.i("yang", "Main End")
Log.i("yang", "Main Continue")
Thread.sleep(500)
mJob.cancel()
Log.i("yang", "Main End")
// log
2025-01-06 16:48:17.754 30216-30216 yang com.example.myapplication I Main Start
2025-01-06 16:48:17.757 30216-30216 yang com.example.myapplication I Main Continue
2025-01-06 16:48:17.757 30216-30670 yang com.example.myapplication I IO Start
2025-01-06 16:48:18.257 30216-30216 yang com.example.myapplication I Main End
2025-01-06 16:48:18.758 30216-30670 yang com.example.myapplication I IO is not active