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 ceh = CoroutineExceptionHandler { _, throwable ->
println("Failure with ${throwable.localizedMessage}")
}
supervisorScope {
launch(ceh) {
throw Exception("Exception1")
}
launch {
delay(100)
runBlocking {
val ceh = CoroutineExceptionHandler { _, throwable ->
println("Failure with ${throwable.localizedMessage}")
}
val scope = CoroutineScope(SupervisorJob()+Dispatchers.IO+ceh)
val j = scope.launch {
val c1 = scope.launch {
throw Exception("Exception1")
}
val c2 = scope.launch {
fun main() {
runBlocking {
launch(Dispatchers.Default) {
println("Hello1")
a()
println("Hello2")
}
println("Hello3")
}
}
fun main() {
runBlocking {
// Exception handling ignored for now
launch(Dispatchers.Default) {
println(someTaskWrapped())
}
}
}
suspend fun someTaskWrapped() = suspendCancellableCoroutine<Int> {
it.invokeOnCancellation {
// Cancel any task or handle resources that you want
}
someTask(
object:Callback{
override fun onSuccess(result: Int) {
it.resume(result)
// Resume the calling coroutine with this result
}
interface Callback {
fun onSuccess(result:Int)
fun onFailure(e: Exception)
}
fun someTask(callback: Callback) {
Thread.sleep(1000)
// Written together for brevity but only one will occur
callback.onSuccess(2)
callback.onFailure(Exception("I failed"))
}
val customDispatcher =
Executors.newSingleThreadExecutor().asCoroutineDispatcher()
launch(customDispatcher) {
println("Thread name: ${Thread.currentThread().name}")
withContext(Dispatchers.IO) {
delay(100)
println("Thread name: ${Thread.currentThread().name}")
}
println("Thread name: ${Thread.currentThread().name}")
withTimeout(1000) {
repeat(100) { i ->
println("I'm sleeping $i ...")
delay(500L)
}
}
Output:
I'm sleeping 0 ...
I'm sleeping 1 ...
val job = launch {
try {
// some work with a file
} finally {
// close the file here
}
}
job.cancelAndJoin()
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 now removed the isActive check
// to demonstrate that if a scope is cancelled,
// even an uncooperative coroutine is stopped