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
}
GlobalScope.asyncasyncis the same asasyncin the video?