kotlin async doesn't compile

5.9k Views Asked by At

The following code doesn't compile, although the documentation says it should be as simple as this:

override fun onResume() {
    super.onResume()
    async {
        Log.d("foo", "async")
    }
}

The error is:

...kt: (31, 9): None of the following functions can be called with the arguments supplied:
@Deprecated public fun <T> async(context: CoroutineContext, start: Boolean, block: suspend CoroutineScope.() -> ???): Deferred<???> defined in kotlinx.coroutines.experimental
public fun <T> async(context: CoroutineContext, start: CoroutineStart = ..., block: suspend CoroutineScope.() -> ???): Deferred<???> defined in kotlinx.coroutines.experimental
4

There are 4 best solutions below

0
On BEST ANSWER

In order to use coroutines in an android app it is a must to add a dependency to kotlinx-coroutines-android as described here.

2
On

the async{} method is deprecated from Kotlin 1.1 try:

override fun onResume() {
    super.onResume()
    doAsync {
        Log.d("foo", "async")
    }
}

I suggest to you to read this question

0
On

If you compare signatures listed with https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/async.html, it's very different.

It looks like you are using an old version of coroutines library, and in particular one where context has no default value.

0
On

Also, async function can only be used inside a coroutine or suspend function. So even if you have the correct dependencies, if you try to use async in onResume(), your code cannot compile.