44 lines
1.3 KiB
Plaintext
44 lines
1.3 KiB
Plaintext
![]() |
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
|
||
|
|
||
|
----
|
||
|
suspend fun CoroutineScope.f(): Int {
|
||
|
val resource1 = loadResource1()
|
||
|
val resource2 = loadResource2()
|
||
|
return resource1.size + resource2.size
|
||
|
}
|
||
|
----
|
||
|
|
||
|
== Compliant Solution
|
||
|
|
||
|
Using `suspend`:
|
||
|
----
|
||
|
suspend fun f(): Int {
|
||
|
val resource1 = loadResource1()
|
||
|
val resource2 = loadResource2()
|
||
|
return resource1.size + resource2.size
|
||
|
}
|
||
|
----
|
||
|
|
||
|
Using extension on `CoroutineScope`:
|
||
|
----
|
||
|
fun CoroutineScope.f(): Deferred<Int> = async {
|
||
|
val resource1 = loadResource1()
|
||
|
val resource2 = loadResource2()
|
||
|
resource1.size + resource2.size
|
||
|
}
|
||
|
----
|
||
|
|
||
|
== See
|
||
|
|
||
|
* https://elizarov.medium.com/coroutine-context-and-scope-c8b255d59055[Coroutine Context and Scope]
|