Is runBlocking{} overhead important and is it a pr...
# coroutines
t
Is runBlocking{} overhead important and is it a problem to use too many in an Android app? I have quite a few place in my app that require to return an answer synchronously because I'm extending API that call me on background thread and expect answers. The underlying question, is about the fact that I should keep some non suspend / synchronous functions for those case, or the overhead is so low that it's OK to have quite a few runBlocking and allow me to keep my internals simple and only support suspend functions?
g
It highly depends on your use case. I really curious about your use cases, maybe you could show an example
t
There's many Android things like RemoteViewsService / ChooserTargetService / ContentProvider queries / .... All those require access to the DB and the tools I have around it. They are all called in background thread and expect an answer at the end of the call. I'd like to keep my DB stuff full suspend to avoid duplicating some functions. So runBlocking seems to currently be the only way. If overhead is too much then I'll duplicated code 😉
g
For things like DB or other IO overhead of event queue is almost nothing, why do you worry about overhead of runBlocking? In this case of course just use suspend and if you need integrate with some blocking code, just use runBlocking
t
This was just one part, in what other cases can event queue overhead be important? And we already had a few discussions, but overhead + overhead + overhead = problem 😉 Measuring and optimizing when you have apps used by millions is important, but I'm not able to properly measure that kind of overhead with my current knowledge.
g
I wouldn't worry about this at all until you have some real concerns or bottlenecks
other cases can event queue overhead be important?
Overhead of thread blocking itself is probably higher, but if you have some blocking API you cannot avoid it
t
In that case and another one I could keep some blocking calls to avoid starting a coroutine + thread switch + runBlocking. But I'll guess I'll go with that and measure in prod 🙂
g
Yes, you pay price of coroutine (which is low, just a couple objects)
You shouldn't have any thread switch tho, runBlocking will run coroutines on the same thread
Writing blocking and non blocking versions of the same API just for some cases when you need blocking looks overcomplicated for me without any real gain
t
The suspend call at the end of the chain have withContext(IO) for the real DB access so there will be 2.
It's just a choice to make between performance and maintenance cost 🙂 If performance loss is < maintenance cost then it's OK, if not then it's not OK 😉
All is about choices but require to have proper data to make the choices 😞
g
You can pass context to avoid context switch. Still looks like a premature optimization. Anyway, hard to say something without real code