Joshua Hansen
09/18/2025, 9:27 PMwithContext for every switch between UI and background?
Currently I have:
suspend fun openView(path: Path): MyView {
// Load data
return withContext(Dispatchers.Swing) {
// Create UI View
}
}streetsofboston
09/18/2025, 9:31 PMstreetsofboston
09/18/2025, 9:34 PMsuspend fun loadData(path: Path): Data {
return withContext(Dispatchers.IO) { ... load data in a blocking way ... }
}
suspend fun openView(path: Path): MyView {
val data = loadData(path)
return {
// Create UI View using 'data'
}
}streetsofboston
09/18/2025, 9:34 PMopenView is called from the main ui thread (Dispatchers.Swing)Joshua Hansen
09/18/2025, 9:35 PMstreetsofboston
09/18/2025, 9:36 PMloadData will be called from the UI thread, but as soon as the execution enters the loadData body, then it switches immediately to Dispatchers.IO and the main UI thread will suspend but it won't be blocked.Joshua Hansen
09/18/2025, 9:36 PMstreetsofboston
09/18/2025, 9:37 PMopenView should be called from the UI thread, since its purpose seems to be to create a View, a UI....streetsofboston
09/18/2025, 9:39 PMsuspend fun loadData(path: Path): Data {
return withContext(<http://Dispatchers.IO|Dispatchers.IO>) { ... load data in a blocking way ... }
}
suspend fun openView(path: Path): MyView {
val data = loadData(path)
return withContext(Dispatchers.Swing) {
// Create UI View using 'data'
}
}
should work.
Even if you're certain that openView is not called from the main UI thread, the loadData function wouldn't know that. It should still switch to the Dispatchers.IOstreetsofboston
09/18/2025, 9:42 PM// Running on the UI thread.
...
val data = loadDataInBackground(input)
// ... still running on UI thread here ...
val view = View.createdFromData(data)
// ... still running on UI thread here ...
return view
At least, that is on most UI systems, where UI must be created and manipulated on the main UI thread.Joshua Hansen
09/18/2025, 9:44 PMopenView is called on the UI thread and go with your suggestion. I can call openView inside something like CoroutineScope(Dispatchers.Swing).launch { ... }.Joshua Hansen
09/18/2025, 9:44 PM