Anko: Why use bg() instead of async()?

Created on 27 Nov 2017  路  5Comments  路  Source: Kotlin/anko

I started using Kotlin coroutines on Android last week 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, but with its own thread pool instead of CommonPool:

@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() or CommonPool inefficient in some way for Android apps?

It'd be great if this information is added to the Anko Wiki so devs know why they should choose bg().

question

All 5 comments

@yanex gentle bump. 馃槃

I found myself not using bg() since it does't allow usage of Ref<> values.

bg{
    ref()  // compiler doesn't let this through
}
async(FixedCoroutineContext){ // this is a fixed threadpool context
    ref() //this is fine
}

Kotlin 1.2.10, Anko 0.10.4 I get "suspension function can be called only form within coroutine body".

work is in progress to let crossinlinework with suspend: https://youtrack.jetbrains.com/issue/KT-19159

what about the documentation update? ...

bg is being removed, it's unnecessary.

Was this page helpful?
0 / 5 - 0 ratings