10

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?

3
  • you prblby need some scope, for example GlobalScope.async Commented Sep 3, 2019 at 10:54
  • are you certain that your async is the same as async in the video? Commented Sep 3, 2019 at 11:33
  • I would strongly suggest against creating async functions. Usually, there is better way to have your problem solved. Can you please describe what problem you are trying to solve with async function? Commented Sep 3, 2019 at 20:48

1 Answer 1

20

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

Just wanted to mention that the third solution won't run multiple calls to doWorkAsync concurrently (unlike the other solutions) because it creates a new scope with coroutineScope.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.