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.connectActivate {
// Launch coroutines on the GTK main dispatcher
CoroutineScope(Dispatchers.Main).launch {
// Your UI code here
}
}
application.connectShutdown {
GtkDispatcher.cancel()
gtkMainThread.cancel()
}
application.run()
}
}

In this example:

  • We create a dedicated thread (gtkMainThread) for bootstrapping GTK.

  • Inject GtkDispatcher as Dispatchers.Main to ensure coroutines use the GTK main loop.

  • Use withContext(gtkMainThread) to initialize GTK on the dedicated thread.

  • Launch coroutines using Dispatchers.Main for UI interactions.

See also

Dispatchers.Main

Properties

Link copied to clipboard
open val immediate: <Error class: unknown class>

Functions

Link copied to clipboard
open fun dispatch(context: <Error class: unknown class>, block: <Error class: unknown class>)
Link copied to clipboard
open fun invokeOnTimeout(timeMillis: Long, block: <Error class: unknown class>, context: <Error class: unknown class>): <Error class: unknown class>
Link copied to clipboard
open fun isDispatchNeeded(context: <Error class: unknown class>): Boolean
Link copied to clipboard
open fun scheduleResumeAfterDelay(timeMillis: Long, continuation: <Error class: unknown class><Unit>)
Link copied to clipboard
open override fun toString(): String