Skip to content

Instantly share code, notes, and snippets.

@viktorklang
Created April 19, 2012 17:58
Show Gist options
  • Save viktorklang/2422659 to your computer and use it in GitHub Desktop.
Save viktorklang/2422659 to your computer and use it in GitHub Desktop.
Akka Futures in the Swing Event Dispatch Thread
// © 2012 Viktor Klang
import akka.dispatch.ExecutionContext
import javax.swing.SwingUtilities
import java.util.concurrent.Executor
//
object SwingExecutionContext {
implicit val swingExecutionContext: ExecutionContext = ExecutionContext.fromExecutor(new Executor {
def execute(command: Runnable): Unit = SwingUtilities invokeLater command
})
}
// Now all you need to do is to use it
import SwingExecutionContext._
Future {
}
// Enjoy!
@wookietreiber
Copy link

Thanks, Viktor!

I was looking exactly for something like this.

Would be so nice to have this in the standard library, now that SIP 14 is in -- is this planned / already done? Care to open a pull request for this in scala.swing.Swing?

I would vote for this being not implicit in scala.swing.Swing, so one has to explicitly set it implicit. I guess this would avoid bugs.

Standard library:

package scala.swing

// imports

object Swing {
  // ...
  val swingExecutionContext: ExecutionContext = ExecutionContext.fromExecutor(new Executor {
    def execute(command: Runnable): Unit = SwingUtilities invokeLater command
  })
  // ...
}

Either your example or even SwingWorker simulation:

package org.example

// imports

object AwesomeApp {
  val label = new Label("...")
  // ...
  def mySwingWorkerSimulation() {
    implicit val ec = ...
    val f = future { "awe" + "some" }
    implicit val ec = Swing.swingExecutionContext
    f onSuccess {
      case s  label.text = s
    }
  }
  // ...
}

@viktorklang
Copy link
Author

Hi!

Sorry for the late reply, just saw this.

I don't think it's needed to add to scala swing since it's just like 4 lines of code :-)

Cheers,

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment