aboutsummaryrefslogtreecommitdiffstats
path: root/ui/kotlinx-coroutines-swing/test/examples/swing-example.kt
diff options
context:
space:
mode:
Diffstat (limited to 'ui/kotlinx-coroutines-swing/test/examples/swing-example.kt')
-rw-r--r--ui/kotlinx-coroutines-swing/test/examples/swing-example.kt39
1 files changed, 39 insertions, 0 deletions
diff --git a/ui/kotlinx-coroutines-swing/test/examples/swing-example.kt b/ui/kotlinx-coroutines-swing/test/examples/swing-example.kt
new file mode 100644
index 00000000..cadb4681
--- /dev/null
+++ b/ui/kotlinx-coroutines-swing/test/examples/swing-example.kt
@@ -0,0 +1,39 @@
+/*
+ * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
+ */
+
+package examples
+
+import kotlinx.coroutines.*
+import kotlinx.coroutines.swing.*
+import java.text.*
+import java.util.*
+import java.util.concurrent.*
+import kotlin.coroutines.*
+
+fun log(msg: String) = println("${SimpleDateFormat("yyyyMMdd-HHmmss.sss").format(Date())} [${Thread.currentThread().name}] $msg")
+
+suspend fun makeRequest(): String {
+ log("Making request...")
+ return suspendCoroutine { c ->
+ ForkJoinPool.commonPool().execute {
+ c.resume("Result of the request")
+ }
+ }
+}
+
+fun display(result: String) {
+ log("Displaying result '$result'")
+}
+
+fun main(args: Array<String>) = runBlocking(Dispatchers.Swing) {
+ try {
+ // suspend while asynchronously making request
+ val result = makeRequest()
+ // example.display result in UI, here Swing dispatcher ensures that we always stay in event dispatch thread
+ display(result)
+ } catch (exception: Throwable) {
+ // process exception
+ }
+}
+