Search code examples
kotlincoroutinekotlinx.coroutines

Async won't compile because of multiple implementations in source


I am trying to run the following code but it's not running because the compiler doesn't know which version of the async method to call. How do I tell it which one to call?

v

ar counter=0
val workerA=asyncIncrement(5000)
val workerB=asyncIncrement(100)
workerA.await()
workerB.await()

print("counter = $counter")

fun asyncIncrement(by:Int)=async{
    for(i in 1..by){
        counter++
    }
}

Just copy and paste the code into a scratch file or wherever and you should see the same compiler error


Solution

  • From Kotlin 1.3 you need to call async on a scope. In this example I have chosen the GlobalScope. But it doesn't matter which scope you choose, you always have to explicitly import the asyncextension function;

    import kotlinx.coroutines.GlobalScope
    import kotlinx.coroutines.async
    import kotlinx.coroutines.runBlocking
    import java.util.concurrent.atomic.AtomicInteger
    
    
    fun main(args: Array<String>) {
    
        val counter=AtomicInteger(0)
    
        fun asyncIncrement(by:Int)= GlobalScope.async{
            for(i in 1..by){
                counter.incrementAndGet()
            }
        }
    
        val workerA=asyncIncrement(5000)
        val workerB=asyncIncrement(100)
        runBlocking {
            workerA.await()
            workerB.await()
        }
    
        print("counter = $counter")
    }
    

    BTW: I changed the variable counter from int to an AtomicInteger because the two async blocks may run in different threads. And I introduced runBlocking, because await has to run in a suspend function.