https://kotlinlang.org logo
#coroutines
Title
# coroutines
d

Davide Giuseppe Farella

10/06/2020, 9:37 AM
Hello guys, given a function like
Copy code
suspend fun getThree() = 
  withContext(IO) {
    val one = async { getOne() }
    val two = async { getTwo() }
    
    one.await() + two.await()
  }
would be better to be wrapper in a
coroutineScope
or would the
withContext
be enough?
o

orafaaraujo

10/06/2020, 9:43 AM
Hello, Davide using a scope you will be protected against possible leaks, because the scope will be attached to your view/viewmodel lifecycle
withContext
is more to switch between dispatchers
in you example, the scope will be handle on where
getThree()
will be called, so I think to switch the dispatcher to IO is fine 🙂
g

gildor

10/06/2020, 9:46 AM
I think it’s wrong explanation from Rafael, in terms of attaching to scope both of them create scope and not different, but withContext also switches scope
using a scope you will be protected against possible leaks
It’s true, but it’s it’s also true for withContext, because with context is create a scope, same as coroutine scope, but also switch dispatcher
🙏 2
👍 1
d

Davide Giuseppe Farella

10/06/2020, 9:47 AM
Thank you guys 🙂
g

gildor

10/06/2020, 9:47 AM
so you can think about withContext as coroutineScope + context switching
🙏 1
another question, do you really need withContext(IO) there or not, I see a lot of similar cases, when it really not needed, because getOne() and getTwo() or already asyncronous, or should provide asyn wrapper
👍 2
d

Davide Giuseppe Farella

10/06/2020, 4:29 PM
Yes, that absolutely makes sense, should take a look into it! Thanks!
4 Views