Colton Idle
09/17/2019, 1:40 PMfun button1Clicked() {
GlobalScope.launch {
Toast.makeText(this@MainActivity, doSomethingLong(), Toast.LENGTH_LONG).show()
}
Toast.makeText(this@MainActivity, "Hello", Toast.LENGTH_LONG).show()
}
suspend fun doSomethingLong(): String =
withContext(Dispatchers.Default) {
delay(3000)
return@withContext "World"
}
Evan R.
09/17/2019, 1:47 PMDispatchers.Main
? That will cause those toast calls to run on the UI thread rather than in GlobalScope.Colton Idle
09/17/2019, 1:49 PMahulyk
09/17/2019, 1:49 PMfun button1Clicked() {
GlobalScope.launch(Main) {
val result = withContext(IO) { doSomethingLong() }
Toast.makeText(this@MainActivity, result, LENGTH_LONG).show()
}
Evan R.
09/17/2019, 1:57 PMThe default dispatcher that is used when coroutines are launched in GlobalScope is represented by Dispatchers.Default and uses a shared background pool of threads, so launch(Dispatchers.Default) { ... } uses the same dispatcher as GlobalScope.launch { ... }.
.launch()
only inherits a scope when it is launched within an existing coroutine scope. Because you were using GlobalScope as its scope and did not specify a different one in the parameter to .launch()
, it used Dispatchers.Default instead of Dispatchers.Main.Colton Idle
09/17/2019, 2:18 PMfun button1Clicked() {
GlobalScope.launch(Dispatchers.Main) {
val result = withContext(<http://Dispatchers.IO|Dispatchers.IO>) { doSomethingLong() }
Toast.makeText(this@MainActivity, result, Toast.LENGTH_SHORT).show()
}
}
suspend fun doSomethingLong(): String =
withContext(Dispatchers.Default) {
delay(3000)
return@withContext "World"
}
vs
fun button1Clicked() {
GlobalScope.launch(Dispatchers.Main) {
val result = withContext(<http://Dispatchers.IO|Dispatchers.IO>) { doSomethingLong() }
Toast.makeText(this@MainActivity, result, Toast.LENGTH_SHORT).show()
}
}
suspend fun doSomethingLong(): String {
delay(3000)
return "World"
}
I know this is a small/dumb example, but maybe there's a best way to do this? Should I always try to have the scope declared inside of the method doing the long running work as best practice?Evan R.
09/17/2019, 2:21 PMColton Idle
09/17/2019, 2:23 PMEvan R.
09/17/2019, 2:23 PMgildor
09/17/2019, 2:28 PM