![github-actions[bot]](/assets/img/avatar_default.png)
* Create rule S6316 * Update metadata.json * Update rule.adoc * Update rules/S6316/kotlin/metadata.json Co-authored-by: Johann Beleites <63855942+johann-beleites-sonarsource@users.noreply.github.com> * Update rules/S6316/kotlin/rule.adoc Co-authored-by: Johann Beleites <63855942+johann-beleites-sonarsource@users.noreply.github.com> * Update rules/S6316/kotlin/rule.adoc Co-authored-by: Johann Beleites <63855942+johann-beleites-sonarsource@users.noreply.github.com> * Update rules/S6316/kotlin/rule.adoc Co-authored-by: Johann Beleites <63855942+johann-beleites-sonarsource@users.noreply.github.com> * Update rules/S6316/kotlin/rule.adoc Co-authored-by: Johann Beleites <63855942+johann-beleites-sonarsource@users.noreply.github.com> Co-authored-by: margarita-nedzelska-sonarsource <margarita-nedzelska-sonarsource@users.noreply.github.com> Co-authored-by: margarita-nedzelska-sonarsource <70522623+margarita-nedzelska-sonarsource@users.noreply.github.com> Co-authored-by: Johann Beleites <63855942+johann-beleites-sonarsource@users.noreply.github.com>
38 lines
1.1 KiB
Plaintext
38 lines
1.1 KiB
Plaintext
Sometimes there is the need to cancel the execution of a coroutine after a given period of time. You can do this manually by combining the `delay()` and `cancel()` functions. However, this technique is verbose and error-prone. An easier way to manage timeouts is using the function `withTimeout()` or `withTimeoutOrNull()`.
|
|
|
|
The `withTimeout` function will throw a `TimeoutCancellationException` when the timeout is reached, while `withTimeoutOrNull` will simply return `null` instead.
|
|
|
|
This rule raises an issue if timeout mechanisms are implemented manually instead of using appropriate built-in functions.
|
|
|
|
== Noncompliant Code Example
|
|
|
|
----
|
|
suspend fun main() {
|
|
coroutineScope {
|
|
val job = launch {
|
|
delay(2000L)
|
|
println("Finished")
|
|
}
|
|
delay(500L)
|
|
job.cancel()
|
|
}
|
|
}
|
|
----
|
|
|
|
== Compliant Solution
|
|
|
|
----
|
|
suspend fun main() {
|
|
coroutineScope {
|
|
withTimeoutOrNull(1000L){
|
|
delay(2000L)
|
|
println("Finished")
|
|
}
|
|
}
|
|
}
|
|
----
|
|
|
|
== See
|
|
|
|
* https://kotlinlang.org/docs/cancellation-and-timeouts.html[Cancellation and timeouts]
|