Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create async function in Kotlin

I am trying to create a async function in kotlin coroutine, this is what I tried by following a tutorial:

fun doWorkAsync(msg: String): Deferred<Int> = async {
    delay(500)
    println("$msg - Work done")
    return@async 42
}

But in this code the async can't be resolved by compiler, but the tutorial video shows it worked fine. Is it because the tutorial is using old Kotlin coroutines' way of doing things? Then, if so how to create async function?

like image 614
Leem Avatar asked Apr 19 '26 09:04

Leem


1 Answers

When coroutines have experimental API it was possible to write just

async {
    // your code here
}

but in stable API you should provide a CoroutineScope where coroutine will run. You can do it in many ways:

// should be avoided usually because you cannot manage the coroutine state. For example cancel it etc
fun doWorkAsync(msg: String): Deferred<Int> = GlobalScope.async {
    delay(500)
    println("$msg - Work done")
    return@async 42
}

or

// explicitly pass scope to run in
fun doWorkAsync(scope: CoroutineScope, msg: String): Deferred<Int> = scope.async {
    delay(500)
    println("$msg - Work done")
    return@async 42
}

or

// create a new scope inside outer scope
suspend fun doWorkAsync(msg: String): Deferred<Int> = coroutineScope {
    async {
        delay(500)
        println("$msg - Work done")
        return@async 42
    }
}

or even

// extension function for your scrope to run like 'scope.doWorkAsync("Hello")'
fun CoroutineScope.doWorkAsync(msg: String): Deferred<Int> = async {
    delay(500)
    println("$msg - Work done")
    return@async 42
}
like image 188
Andrei Tanana Avatar answered Apr 21 '26 00:04

Andrei Tanana



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!