Hello everyone :wave: I’m wondering if there is an...
# coroutines
j
Hello everyone 👋 I’m wondering if there is any merit or risks in combining
async
and
withContext(<http://Dispatches.IO|Dispatches.IO>)
to be able to execute blocking code, in particular making multiple IO calls with Spring RestTemplate, in an asynchronous fashion like so:
Copy code
fun <T> CoroutineScope.myRestTemplateAsync(
    context: CoroutineContext = EmptyCoroutineContext,
    start: CoroutineStart = CoroutineStart.DEFAULT,
    block: suspend CoroutineScope.() -> T
): Deferred<T> {
    return async(context, start) {
        withContext(<http://Dispatchers.IO|Dispatchers.IO>) { block() }
    }
}
The full description, observations, and code samples are in this SO Post
k
you can just do
async(context + <http://Dispatchers.IO|Dispatchers.IO>)
j
Thanks @knthmn, It works great!
k
Just to clarify, there is no risk of using
async()
and then
withContext()
. Both versions replace whatever
Dispatcher
specified in
context
with
<http://Dispatchers.IO|Dispatchers.IO>
👍 1