something that has confused me with coroutines is ...
# android
a
something that has confused me with coroutines is that you often see things done with runBlocking. Doesn't that sort of defeat the purpose of making a thing a suspend function?
For instance if you are on the main thread and calling into a viewModel to load from DB in a suspend function using the runBlocking builder - is that not equivalent to just calling the blocking version without using coroutines at all?
b
Just don't do that as much as possible. It was designed for the cases when you need to perform blocking operation.
From docs:
This function should not be used from a coroutine. It is designed to bridge regular blocking code to libraries that are written in suspending style, to be used in main functions and in tests.
a
I guess this goes back before coroutines to the argument that db INSERTs are fast enough for main thread.
most Room/Coroutine examples I see do this
j
Those are wrong then
a
👍 Good to know. Trying to form a True North for coroutine usage. Seems to be lots of incorrect stuff out there.
b
Could you show these examples? Inserts may take a while if there is another transaction for example
a
Is it true then that correct usage of coroutine/Mvvm will most certainly make use of an async vehicle like LiveData or RxJava? (or Flow)
Copy code
fun getAllSprockets(): List<Sprockets> = runBlocking {
    val deferred: Deferred<List<Sprockets>> = async {
      repository.getAllSprockets()
    }
    deferred.await()
  }
consider something like this as a public viewmodel interface
from what I'm hearing, this is flat wrong
which jives with my other opinion that having
getters
on a VM is an antipattern
b
wrapping repository call to async and then to runBlocking doesn't make any sense to me 🤷 it could be
Copy code
suspend fun getAllSprockets() = repository.getAllSprockets()
if repository call is suspend fun or
Copy code
fun getAllSprockets() = repository.getAllSprockets()
if it blocking or
Copy code
suspend fun getAllSprockets() = runBlocking { return repository.getAllSprockets()
}
if repository call is suspend fun, but you need blocking
👍 1
a
OK cool so it's not just me thinking this is weird 🙂 . In the first case you are exposing a suspend function to the consumer of the VM which I suppose is just moving the problem. Eventually I guess you'd want to use a launch or async builder to wrap that
for anyone following this thread - I found this very useful : https://proandroiddev.com/how-to-make-sense-of-kotlin-coroutines-b666c7151b93 . Best thing I've read yet to make sense of things