Recomendation for what api/syntax/idiom to use whe...
# coroutines
d
Recomendation for what api/syntax/idiom to use when running in a coroutine or suspendinmg function and calling a known 'blocking' API (e.g. normal java IO blocking apis). Docs say do NOT use runBlocking() -- so ok. what do I use ?
g
Yes, sure runBlocking is a wrong choice, runBlocking blocks thread until coroutines inside are suspended, so it’s not for this case. Approach is pretty simple actually, just create custom coroutine dispatcher (there is
newFixedThreadPoolContext
function and extension to convert
ThreadExecutor
to Context) this dispatcher will be intentionally blocking and should be used to wrap blocking code. Than just use:
Copy code
withContext(IoDispatcher) {
    someBlockingCall()
}
Or with any other coroutine builder, depending on case
2
w
If you want to emulate the
IO
scheduler of Rx you can also use
Executors.newCachedThreadPool().asCoroutineDispatcher()
d
re: Andrey Mischenko ! Thanks ! You worded the reply slighlyt differnetly then I have read before and now it makes sense. If Iread this right the 'blocking' in runBlocking{} means that the CALLING context is EXPLICITLY blocked until the all CALLED contexts are suspended. Thats quite different then the CALLED Contexts are expected to 'block' !!
Looking quickly over some API's I think Im (finally) seeing a pattern/convention founded in a language symantic (natural) assumption that differs from my own. Example: to my unconcious read 'run blocking' means 'to run <something> that is 'blocking' -- but in this case it 'to run <something> while blockign <this>' , similarly I would read "sortMatching" to mean "sort <this> when it is matching <something>" -- the object being the argument. But in some languages ( I belive Dutch is one) the reverse is the norm .. which leads to a english-joke about translating "Throw the cow some hay over the fence" to "Throw the Cow over the Fence some Hay" 🙂