49 lines
1.4 KiB
Plaintext
49 lines
1.4 KiB
Plaintext
== Why is this an issue?
|
|
|
|
There are two ways to define asynchronous functions in Kotlin:
|
|
|
|
* using the modifier `suspend` in the function declaration
|
|
* creating an extension function on `CoroutineScope` (or passing it as a parameter)
|
|
|
|
The `suspend` modifier is generally used for functions that might take some time to complete. The caller coroutine might be potentially suspended.
|
|
|
|
Functions that return results immediately but start a coroutine in the background should be written as extension functions on `CoroutineScope`. At the same time, these functions should not be declared `suspend`, as suspending functions should not leave running background tasks behind.
|
|
|
|
|
|
=== Noncompliant code example
|
|
|
|
[source,kotlin]
|
|
----
|
|
suspend fun CoroutineScope.f(): Int {
|
|
val resource1 = loadResource1()
|
|
val resource2 = loadResource2()
|
|
return resource1.size + resource2.size
|
|
}
|
|
----
|
|
|
|
=== Compliant solution
|
|
|
|
Using `suspend`:
|
|
[source,kotlin]
|
|
----
|
|
suspend fun f(): Int {
|
|
val resource1 = loadResource1()
|
|
val resource2 = loadResource2()
|
|
return resource1.size + resource2.size
|
|
}
|
|
----
|
|
|
|
Using extension on `CoroutineScope`:
|
|
[source,kotlin]
|
|
----
|
|
fun CoroutineScope.f(): Deferred<Int> = async {
|
|
val resource1 = loadResource1()
|
|
val resource2 = loadResource2()
|
|
resource1.size + resource2.size
|
|
}
|
|
----
|
|
|
|
== Resources
|
|
|
|
* https://elizarov.medium.com/coroutine-context-and-scope-c8b255d59055[Coroutine Context and Scope]
|