https://kotlinlang.org logo
#android
Title
# android
a

Andy Gibel

12/16/2019, 4:59 PM
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

bezrukov

12/16/2019, 5:16 PM
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

Andy Gibel

12/16/2019, 5:18 PM
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

jw

12/16/2019, 5:19 PM
Those are wrong then
a

Andy Gibel

12/16/2019, 5:21 PM
👍 Good to know. Trying to form a True North for coroutine usage. Seems to be lots of incorrect stuff out there.
b

bezrukov

12/16/2019, 5:21 PM
Could you show these examples? Inserts may take a while if there is another transaction for example
a

Andy Gibel

12/16/2019, 5:21 PM
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

bezrukov

12/16/2019, 5:43 PM
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

Andy Gibel

12/16/2019, 5:49 PM
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