I want to cancel kotlin coroutine if it takes longer than a certain time.
This is what I am doing:
GlobalScope.launch(Dispatchers.Main) {
val userOne = async(Dispatchers.IO) { Page_Load_Times() }.await()
Log.d("Tag", "Long Running task: $userOne")
}
suspend fun Page_Load_Times(): String? {
val startTime: Long = 0
var endTime: Long = 0
delay(5000) // if it is greater a certain time, eg 1000, I want to cancel the thread and return
return "Hey there"
}
How to cancel kotlin coroutine if it takes longer than a certain period of time?
There are built in suspending functions for that: withTimeout and withTimeoutOrNull.
Just invoke it with specified timeout:
GlobalScope.launch(Dispatchers.Main) {
val userOne = withContext(Dispatchers.IO) {
withTimeoutOrNull(5000) { Page_Load_Times() }
}
Log.d("Tag", "Long Running task: $userOne")
}
Then your userOne becomes null if it times out.
I want to share a good example with you through the documentation. I hope it inspires.
val job = launch {
repeat(1000) { i ->
println("job: I'm sleeping $i ...")
delay(500L)
}
}
delay(1300L) // delay a bit
println("main: I'm tired of waiting!")
job.cancel() // cancels the job
job.join() // waits for job's completion
println("main: Now I can quit.")
It produces the following output:
job: I'm sleeping 0 ...
job: I'm sleeping 1 ...
job: I'm sleeping 2 ...
main: I'm tired of waiting!
main: Now I can quit.
Source-Doc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With