GtkDispatcher
Provides a dispatcher for GTK's main loop.
Work dispatched via this dispatcher is guaranteed to be executed on GTK's main/UI thread.
Note: To use Dispatchers.Main with GTK, you need to inject GtkDispatcher as the main dispatcher. This can be done using internal APIs:
@Suppress("INVISIBLE_MEMBER", "INVISIBLE_REFERENCE")
Dispatchers.setMain(GtkDispatcher)A feature request for a stable API to set the main dispatcher is being tracked here: Kotlin Coroutines Issue #4286.
Bootstrapping Example
When starting a GTK application, you need to initialize the GTK environment on a dedicated thread and set up the main dispatcher. Here's a simplified example:
fun main() = runBlocking {
// Bootstrap GTK on a dedicated thread
val gtkMainThread = newSingleThreadContext("GTK-Main")
// Inject GtkDispatcher as the Main dispatcher
@Suppress("INVISIBLE_MEMBER", "INVISIBLE_REFERENCE")
Dispatchers.setMain(GtkDispatcher)
// Start the GTK application
withContext(gtkMainThread) {
// Initialize GTK application and start the main loop
val application = Application("com.example.myapp", ApplicationFlags.DEFAULT_FLAGS)
application.onActivate {
// Launch coroutines on the GTK main dispatcher
CoroutineScope(Dispatchers.Main).launch {
// Your UI code here
}
}
application.onShutdown {
GtkDispatcher.cancel()
gtkMainThread.cancel()
}
application.run()
}
}In this example:
We create a dedicated thread (
gtkMainThread) for bootstrapping GTK.Inject
GtkDispatcherasDispatchers.Mainto ensure coroutines use the GTK main loop.Use
withContext(gtkMainThread)to initialize GTK on the dedicated thread.Launch coroutines using
Dispatchers.Mainfor UI interactions.