https://kotlinlang.org logo
Title
n

niqo01

03/10/2020, 6:25 PM
If I am using a library which offers both a synchronous and an asynchronous API to do IO stuff, I am ensure about the pros/cons of using either way: 1. withContext(Dispatchers.IO) { lib.syncAPI() } 2. withContext(Dispatchers.IO) { suspendCancellableCoroutine{ lib*.asyncAPI( object:Listener{ fun onfailure(){} fun onSuccess() ...})}* Option 1 wins on simplicity and I control on my side the thread pool, anything else?
o

octylFractal

03/10/2020, 6:27 PM
with (2) you don't actually need the
withContext
block, as you're actually suspending the coroutine entirely
it's arguably the "better" option since you can avoid blocking a thread anyways, even if the IO pool is large it can still run out
👍 1
z

Zach Klippenstein (he/him) [MOD]

03/10/2020, 6:31 PM
I’d also go with option 2 because it’s using the library’s own async API, which allows the library to potentially optimize how the IO is done (e.g. using async system calls for IO instead of blocking ones)
👍 2
o

octylFractal

03/10/2020, 6:32 PM
a lot of libraries also use the async API even when you're using the "sync" API, by just blocking on a future or equivalent internally. so it cuts down on overhead in that case