Created
August 7, 2019 02:37
-
-
Save aldoKelvianto/4537d45dc38f282b11ae05fa91362476 to your computer and use it in GitHub Desktop.
Demonstrate cancellation in coroutine
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import kotlinx.coroutines.* | |
import java.net.URL | |
fun main() { | |
cancelWhenFetchingDataOverNetwork() | |
// cancelWhenTakeANap() | |
// cancelWhenDoingHeavyComputation() | |
} | |
fun cancelWhenDoingHeavyComputation() = runBlocking { | |
val parentScope = CoroutineScope(SupervisorJob()) | |
parentScope.launch { | |
println("#1") | |
launch { | |
println("#3") | |
fibonacci(1_000) | |
println("#4") | |
} | |
println("#2") | |
} | |
delay(1_000) | |
parentScope.cancel() | |
println("Bye") | |
} | |
fun cancelWhenTakeANap() = runBlocking { | |
val parentScope = CoroutineScope(SupervisorJob()) | |
parentScope.launch { | |
println("#1") | |
launch { | |
println("#3") | |
takeANap() | |
println("#4") | |
} | |
println("#2") | |
} | |
delay(300) | |
parentScope.cancel() | |
delay(300) | |
println("Bye") | |
} | |
fun cancelWhenFetchingDataOverNetwork() = runBlocking { | |
val parentScope = CoroutineScope(SupervisorJob()) | |
parentScope.launch { | |
println("#1") | |
launch { | |
println("#3") | |
fetchDataOverNetwork() | |
println("#4") | |
} | |
println("#2") | |
} | |
delay(1_000) | |
parentScope.cancel() | |
delay(1_000) | |
println("Bye") | |
} | |
suspend fun fetchDataOverNetwork() { | |
val tenSecondInMillis = 10000 | |
val result = URL("https://httpstat.us/200?sleep=$tenSecondInMillis").readText() | |
println("$result") | |
} | |
suspend fun takeANap() { | |
Thread.sleep(1_000) | |
} | |
suspend fun fibonacci(n: Int): Int { | |
return if (n <= 1) { | |
n | |
} else { | |
fibonacci(n - 1) + fibonacci(n - 2) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment