How to run Akka actors in a JavaFX/ScalaFX Application ?
(This is an update of question based on the first answers)
Is the solution to share the same execution context? Meaning having the Actors dispatchers based on the JavaFx ExecutorService ? (The one with which on which it runs UI manipulation code)
Does that mean one agent would represent the UI and be able to manipulate it ? I mean because suggested below if a couple of actor are on the UI ExecutorService, doesn't that mean share a state between agent (the object being the UI)?
Can 2 actors communicate while being on different executor services? I'm asking this because from what is suggested below, some agent would be on the UI Executor Service while other not.
Finally, why using akka as is, with its on Executor context different and using Platform.runLater, might have some consequence on the performance of the UI. I this pose the question of multiple executor service on the same application: Is that bad?
The best way to use scala Futures together with a single-threaded toolkit such as JavaFX would be to define an executor that allows you to execute futures or actors on the thread of the UI Toolkit.
The same problem exists for Swing, which also requires updates to happen on the swing thread. Viktor Klang came up with the following solution Swing Execution Context. Here it is translated for JavaFX:
You would use it like this:
The pipeline of futures can be very complex, as long as the step(s) that interact with JavaFX components are all running on the JavaFX ExecutionContext.
Note: it is up to you whether you make the ForkJoin ec the default and pass the JavaFX ec explicitly or vice versa. It might be a good idea to make the JavaFX ec the default to prevent errors and mark the parts that can run asynchronously explicitly with the ForkJoin ec.
For integrating an Actor based system with a single-threaded UI toolkit there is also a solution. See Swing Actors. All you have to do is to replace the
with
and you're good to go!
If you have a big UI application and just want to spin off some asynchronous operations (loading a file or doing some computation), the futures-based approach is probably preferable. But be careful not to do any interaction (neither read nor write) with JavaFX components in the futures that run asynchronously on the default execution context.
If you have a large actor based system and just want to attach an UI to some parts, having a few actors that run on the JavaFX thread is probably preferable. YMMV.