Recomendation for what api/syntax/idiom to use whe...
# coroutines
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 ?
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
function and extension to convert
to Context) this dispatcher will be intentionally blocking and should be used to wrap blocking code. Than just use:
Copy code
withContext(IoDispatcher) {
Or with any other coroutine builder, depending on case
If you want to emulate the
scheduler of Rx you can also use
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" 🙂