rspec/rules/S6316/kotlin/rule.adoc
github-actions[bot] 3337ef0c1f
Create rule S6316: Kotlin coroutines api for timeouts should be used (#182)
* 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>
2021-07-23 12:31:22 +00:00

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]