maxmello
01/14/2019, 4:25 PMfun doIt() = runBlocking { value = withContext(Dispatchers.Default) { // some calculations } }
vs just doing everything on the main thread? As I understand, runBlocking
will still block the main thread (if doIt
is called from it), is there any practical difference between blocking the main thread by runBlocking
and by just doing some calculations on the main thread?dave08
01/14/2019, 4:33 PMlaunch
and display some kind of progress (or indeterminate progress) indicator and remove it when the calculation is done. That way the user will still have a responsive UI. Unless this calculation is VERY short...maxmello
01/14/2019, 4:36 PMmaxmello
01/14/2019, 4:36 PMdave08
01/14/2019, 4:39 PMsuspend fun calc() = withContext(Dispatchers.Default) { .. }
and launch
on the CoroutineScope
of the Activity or ViewModel or whatever that is by default on Main...dave08
01/14/2019, 4:42 PMmaxmello
01/14/2019, 5:20 PMgroostav
01/14/2019, 6:31 PMmyanmarking
01/16/2019, 11:33 AMdave08
01/16/2019, 11:36 AMlaunch { showWaiting(true); runQuery(); showWaiting(false); }
@myanmarkingmyanmarking
01/16/2019, 11:37 AMmyanmarking
01/16/2019, 11:38 AMgroostav
01/16/2019, 6:51 PMrunblocking
point and the DB.query
point.
I"m also building a desktop UI'd application that has a reasonably slow persistence system. The pattern that I've developed is like this:
fun someUIEventHandler(event: Event){
event.sourceUIControl.disable = true
//with suspension semantics the UI thread will
//continue, so the user could potentially click the
//same button again, which can get your UI into a
//strange way. Better to just disable the button or
//whatever that kicked off this process.
launch(appropriateScope + Dispatchers.Main){
try {
val uiState = ui.getTextAndOtherInfo();
val query = makeQuery(uiState, otherModelState)
val result = withContext(Dispachers.Default) {
DB.execute(query).andMaybeSomeORM()
}
ui.setTextAndOtherState(result)
}
finally {
event.sourceUIControl.disable = false
}
}
}
you can load that up with a bunch of helpers --the most useful for us is a SuspendingDatabaseFacade
that has all the same functions as DB
but tagged with suspend
and wrapping the value in withContext
.