2
votes

I started using Kotlin coroutines on Android today and I noticed that Anko has its own set of helper methods for them. I understand why asReference() exists, but I can't figure out why bg() does, given that the core coroutines lib already has async().

The bg() code is quite simple and it uses async() inside:

@PublishedApi
internal var POOL = newFixedThreadPoolContext(2 * Runtime.getRuntime().availableProcessors(), "bg")

inline fun <T> bg(crossinline block: () -> T): Deferred<T> = async(POOL) {
    block()
}

So what is the advantage of using bg() instead of async()? Is async() inefficient in some way for Android apps?

1

1 Answers

2
votes

As you can see, bg uses POOL as its CoroutineDispatcher, read about it here.

Basically this function only exists to wrap the pool in which these tasks are executed. Using async directly would require you to provide one. So in the end, each task started via bg is ensured to be executed in the same pool.