Is `runBlocking` safe for production if we have he...
# coroutines
a
Is
runBlocking
safe for production if we have helper suspended functions, and are using an interface where it’s okay to block the thread? For instance, I’m building a notification widget, which requires updates to be done in
onDataSetChanged
, before the provider will apply the data
g
What is “safe for production”?
In most cases it’s possible to avoid use runBlocking
and it’s really rare in real code
a
Well say you have a function
suspend fun loadData(): Data
which is suspended purely to ensure that it never gets called on the main thread. You now want to use an interface containing
Copy code
fun a()
fun b()
where you must load the data in
a
. Internally,
b
must execute after the data is loaded. In this case we could make two copies of the data loading function, where one is suspended and one is not. I’m curious if that is necessary or if we can just wrap it in
runBlocking
g
which is suspended purely to ensure that it never gets called on the main thread.
This is really strange case. Why do you need suspend function for this? suspend means that function is async
I think usage of runBlocking is possible of course, but error prone, if this function in future will change and it will be long operation your app will freeze
where you must load the data in
a
. Internally,
b
must execute after the data is loaded.
Still strange for me, can you show example.
a
Is it not a common pattern to specify suspend purely to ensure thread values? I have a bunch of helper functions that by themselves are not suspend functions. However, they need to execute on the main thread or in the background. Wrapping the logic with suspension makes it easier for the caller, since they no longer need to worry about managing context. For now I’ve opted just to make a function for the non suspended version, then wrap it again for other use cases.
g
Is it not a common pattern to specify suspend purely to ensure thread values?
What exactly do you mean? To switch to main thread?
if so, yeas, it’s completely fine
but use runBlocking is dangerous, what if this function will add some network request, or delay or other long operations This will be completely valid from function point of view, but runBlocking will just block thread completely in this case
To avoid this, just wrap it with
launch
, it will work for 99% cases
s
The only use I have for runBlocking in one of my libraries is to close resources on program exit in JVM code, since the runtime hook for program close is a thread and not a coroutine
1
g
Same for us, we use only on app creation and carefully, only for file io, and in some cases for resources cleanup