thana
07/14/2019, 1:41 PMsuspend
or just call a coroutine from within that method?streetsofboston
07/14/2019, 1:54 PMsuspend
function returns a result, waits for all the stuff inside the suspend
function to be done/finished before it returns/resumes.
A call to CoroutineScope.launch
or CoroutineScope.async
returns immediately. The coroutine, launched by these two function, runs now concurrently with the code that launched it.thana
07/14/2019, 1:58 PMsuspend
and start coroutines as late es possible, or i could start a coroutine as early as possible and just use different contextsstreetsofboston
07/14/2019, 2:50 PMCoroutineScope
, e.g. val uiScope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
Using this uiScope
, you start initiating your asynchronous stuff, like fetching data from the network/db and then putting it onto the screen. E.g.
uiScope.launch {
val result = dataSource.getData(input)
val dataToPutOntoScreen = result.toUiResult() // some (simple) transformation
view.showUI(dataToPutOntoScreen)
}
Your dataSource : DataSource
could have an implementation that goes to an actual database:
class DataSource {
...
suspend fun getData(input: Input): SomeResult = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
val db = dbService.getDB()
val cursor = dp.query { .... } // some query
if (cursor.moveFirst) { cursor.toSomeResult() } else { NoResult }
}
...
}
Here you see the UI creates a scope that runs its Coroutines onthe Main-UI thread. And the DataSource runs its query methods on an IO scheduler by calling withContext
.thana
07/14/2019, 3:19 PMsuspend
on service level, and spread suspend everywhere below" 🤔streetsofboston
07/14/2019, 4:29 PMthana
07/14/2019, 4:31 PMstreetsofboston
07/14/2019, 4:33 PMlaunch
or async
) when you need to run them in parallel (google for the functions coroutineScope { ... }
and supervisorScope { ... }
for more info on that)thana
07/14/2019, 4:37 PMasync
in a dedicated coroutineeScope
because it feels very natural, i realized that async
already is a coroutine builder, but i only thought of launch
when i asked the questionlaunch
is like the entry point into "non traditional code from a java perspective" while async
is not... propably and odd thining 😉streetsofboston
07/14/2019, 5:19 PMCoroutineScope.launch
to move from the regular function world into the suspend function world. You'd use launch
since your UI is a pure side-effect, writing stuff the the screen, not expecting any result, really.
In the suspend function world, you'd mostly use plain suspend
functions, an occasional launch
for doing other side-effects (e.g. logging), some async
calls for obtaining some results that can be calculated in parallel with the rest of your suspend
function's code.thana
07/14/2019, 6:06 PM