Skip to content

Instantly share code, notes, and snippets.

@unix-junkie
Last active January 15, 2019 12:49
Show Gist options
  • Save unix-junkie/ad6db526764a97f8d3bf210564d3cd07 to your computer and use it in GitHub Desktop.
Save unix-junkie/ad6db526764a97f8d3bf210564d3cd07 to your computer and use it in GitHub Desktop.
A Kotlin coroutine showcase featuring two custom dispatchers
package com.example
import kotlinx.coroutines.experimental.*
import kotlinx.coroutines.experimental.swing.Swing
import java.awt.BorderLayout
import java.awt.Dimension
import java.awt.Font
import java.io.IOException
import java.io.PrintWriter
import java.io.StringWriter
import java.nio.file.Files
import java.nio.file.Paths
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import javax.swing.JFrame
import javax.swing.JPanel
import javax.swing.JScrollPane
import javax.swing.JTextArea
import kotlin.concurrent.thread
import kotlin.coroutines.experimental.CoroutineContext
object IoDispatcher : CoroutineDispatcher() {
private val ioExecutor: ExecutorService = Executors.newSingleThreadExecutor {
thread(false, name = "I/O Queue", block = it::run)
}
override fun dispatch(context: CoroutineContext, block: Runnable) {
ioExecutor.submit(block)
}
override fun toString() = "I/O Queue"
}
val Dispatchers.SingleThreadedIo: CoroutineDispatcher
get() = IoDispatcher
@Throws(IOException::class)
suspend fun readFile(): String {
return withContext(Dispatchers.SingleThreadedIo) {
Files.newBufferedReader(Paths.get("/etc/passwd")).readText()
}
}
fun main(vararg args: String) {
GlobalScope.launch(Dispatchers.Swing) {
val frame = JFrame().apply {
defaultCloseOperation = JFrame.EXIT_ON_CLOSE
preferredSize = Dimension(640, 480)
}
val textArea = JTextArea().apply {
font = Font("Courier New", Font.PLAIN, 12)
}
val scrollPane = JScrollPane()
scrollPane.viewport.add(textArea)
val contentPane = frame.contentPane as JPanel
contentPane.apply {
layout = BorderLayout()
}
contentPane.add(scrollPane, BorderLayout.CENTER)
frame.pack()
frame.isVisible = true
textArea.isEditable = false
try {
textArea.text = readFile()
} catch (ioe: IOException) {
textArea.text = StringWriter().also {
ioe.printStackTrace(PrintWriter(it))
}.buffer.toString()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment