SlideShare ist ein Scribd-Unternehmen logo
1 von 35
Downloaden Sie, um offline zu lesen
JavaFX GUI architecture
with Clojure core.async
@friemens
GUIs are challenging
GUI implementation causes significant LOC numbers
GUIs require frequent changes
Automatic GUI testing is expensive
GUI code needs a suitable architecture
Model Controller
View
Model Controller
View
MVC makes you think of mutable things
MVC Variations
MVP
a.k.a
Passive View
View
Model
Presenter View
Model
View
Model
MVVM
a.k.a
PresentationModel
A real-world OO GUI architecture
ControllerViewModel
ViewImpl
UI Toolkit Impl
UIView
Other parts of the system
two-way
databinding
updates
action
events
only data!
Benefits so far
ControllerViewModel
ViewImpl
UI Toolkit Impl
UIView
Other parts of the system
two-way
databinding
updates
action
events
only data!
Dumb Views => generated code
Dumb ViewModels => generated code
Controllers are unit-testable
Remaining annoyances
ControllerViewModel
ViewImpl
UI Toolkit Impl
UIView
Other parts of the system
two-way
databinding
updates
action
events
only data!
Unpredicatble execution paths
Coordination with long runnning code
Merging of responses into ViewModels
Window modality is based on a hack
Think again... what is a user interface?
events
state
1) is a representation of system state
A user interface ...
{:name {:value "Foo"
:message nil}
:addresses [{:name "Bar"
:street "Barstr"
:city "Berlin"}
{:name "Baz"
:street "Downstr"
:city "Bonn"}]
:selected [1]}
events
state
1) is a representation of system state
2) allows us to transform system state
A user interface ...
{:name {:value "Foo"
:message nil}
:addresses [{:name "Bar"
:street "Barstr"
:city "Berlin"}
{:name "Baz"
:street "Downstr"
:city "Bonn"}]
:selected [1]}
2)
1)
A user interface ...
… consists of two functions ...
which – for technical reasons –
need to be executed asynchronously.
[state] → ⊥ ;; update UI (side effects!)
[state event] → state ;; presentation logic
( )
Asynchronity in GUIs
GUI can become unresponsive
Java FX application thread
Event loop
Your code
Service call
What happens
if a service call
takes seconds?
Keep GUI responsive (callback based solution)
Service call
Your code 1
Your code 2
Use other thread
Java FX application thread
Event loop Some worker thread
Delegate execution
Schedule to
event loop
Meet core.async: channels go blocks+
Based on Tony Hoare's CSP* approach (1978).
Communicating Sequential Processes
*
(require '[clojure.core.async :refer
[put! >! <! go chan go-loop]])
(def c1 (chan))
(go-loop [xs []]
(let [x (<! c1)]
(println "Got" x ", xs so far:" xs)
(recur (conj xs x))))
(put! c1 "foo")
;; outputs: Got bar , xs so far: [foo]
a blocking read
make a new channelcreates a
lightweight
process
async write
readwrite
The magic of go
sequential code
in go block
read
write
macro
expansion
state
machine
code snippets
Keep GUI responsive (CSP based solution)
core.async process
core.async process
Java FX application thread
Your code
Update UI
<! >!
<!
put!
go-loop
one per viewexactly one
events
state
Expensive service call: it's your choice
(def events (chan))
(go-loop []
(let [evt (<! events)]
(case ((juxt :type :value) evt)
[:action :invoke-blocking]
(case (-> (<! (let [ch (chan)]
(future (put! ch (expensive-service-call)))
ch))
:state)
:ok (println "(sync) OK")
:nok (println "(sync) Error"))
[:action :invoke-non-blocking]
(future (put! events
{:type :call
:value (-> (expensive-service-call)
:state)}))
[:call :ok] (println "(async) OK")
[:call :nok] (println "(async) Error")))
(recur))
blocking
non-
blocking
ad-hoc new channel
use views events channel
Properties of CSP based solution
„Blocking read“ expresses modality
A views events channel takes ALL async results
✔ long-running calculations
✔ service calls
✔ results of other views
Each view is an async process
Strong separation of concerns
A glimpse of
https://github.com/friemen/async-ui
prototype
JavaFX + Tk-process + many view-processes
JavaFX
Many view processes
One toolkit oriented
process
(run-view)
(run-tk)
Event handler
(spec) (handler)
Each view has one
events channel
Data representing view state
:id ;; identifier
:spec ;; data describing visual components
:vc ;; instantiated JavaFX objects
:data ;; user data
:mapping ;; mapping user data <-> VCs
:events ;; core.async channel
:setter-fns ;; map of update functions
:validation-rule-set ;; validation rules
:validation-results ;; current validation messages
:terminated ;; window can be closed
:cancelled ;; abandon user data
(spec) - View specification with data
(defn item-editor-spec
[data]
(-> (v/make-view "item-editor"
(window "Item Editor"
:modality :window
:content
(panel "Content" :lygeneral "wrap 2, fill"
:lycolumns "[|100,grow]"
:components
[(label "Text")
(textfield "text" :lyhint "growx")
(panel "Actions" :lygeneral "ins 0"
:lyhint "span, right"
:components [(button "OK")
(button "Cancel")])])))
(assoc :mapping (v/make-mapping :text ["text" :text])
:validation-rule-set (e/rule-set :text (c/min-length 1))
:data data)))
attach more
configuration data
a map with initial user data
specify contents
(handler) - Event handler of a view
(defn item-editor-handler
[view event]
(go (case ((juxt :source :type) event)
["OK" :action]
(assoc view :terminated true)
["Cancel" :action]
(assoc view
:terminated true
:cancelled true)
view)))
Using a view
(let [editor-view (<! (v/run-view
#'item-editor-spec
#'item-editor-handler
{:text (nth items index)}))]
. . .)
(defn item-editor-spec
[data]
(-> (v/make-view "item-editor"
(window "Item Editor"
:modality :window
:content
(panel "Content" :lygeneral "wrap 2, fill"
:lycolumns "[|100,grow]"
:components
[(label "Text")
(textfield "text":lyhint "growx")
(panel "Actions" :lygeneral "ins 0"
:lyhint "span, right"
:components [(button "OK")
(button "Cancel")])])))
(assoc :mapping (v/make-mapping :text ["text" :text])
:validation-rule-set (e/rule-set :text (c/min-length 1))
:data data)))
(defn item-editor-handler
[view event]
(go (case ((juxt :source :type) event)
["OK" :action]
(assoc view :terminated true)
["Cancel" :action]
(assoc view
:terminated true
:cancelled true)
view)))
a map with initial user data
spec handler
calling view process waits for callee
You can easily build it yourself!
JavaFX API
update
build
Toolkit
Impl
View process fns
Toolkit process fns
core.clj
tk.clj
builder.clj
binding.clj
bind
< 400 LOC
Wrap up
MVC leads to thinking in terms of mutation
UIs introduce asynchronity
UI is a reactive representation of system state
Thank you for listening!
Questions?
@friemens
www.itemis.de@itemis
https://github.com/friemen/async-ui

Weitere ähnliche Inhalte

Was ist angesagt?

Unity and WebSockets
Unity and WebSocketsUnity and WebSockets
Unity and WebSockets
Josh Glover
 
Load testing with gatling
Load testing with gatlingLoad testing with gatling
Load testing with gatling
Chris Birchall
 
Javascript frameworks: Backbone.js
Javascript frameworks: Backbone.jsJavascript frameworks: Backbone.js
Javascript frameworks: Backbone.js
Soós Gábor
 

Was ist angesagt? (20)

React Native: JS MVC Meetup #15
React Native: JS MVC Meetup #15React Native: JS MVC Meetup #15
React Native: JS MVC Meetup #15
 
MBLTDev15: Egor Tolstoy, Rambler&Co
MBLTDev15: Egor Tolstoy, Rambler&CoMBLTDev15: Egor Tolstoy, Rambler&Co
MBLTDev15: Egor Tolstoy, Rambler&Co
 
Groovy Ecosystem - JFokus 2011 - Guillaume Laforge
Groovy Ecosystem - JFokus 2011 - Guillaume LaforgeGroovy Ecosystem - JFokus 2011 - Guillaume Laforge
Groovy Ecosystem - JFokus 2011 - Guillaume Laforge
 
Reactive, component 그리고 angular2
Reactive, component 그리고  angular2Reactive, component 그리고  angular2
Reactive, component 그리고 angular2
 
C#on linux
C#on linuxC#on linux
C#on linux
 
Unity and WebSockets
Unity and WebSocketsUnity and WebSockets
Unity and WebSockets
 
Load testing with gatling
Load testing with gatlingLoad testing with gatling
Load testing with gatling
 
"Service Worker: Let Your Web App Feel Like a Native "
"Service Worker: Let Your Web App Feel Like a Native ""Service Worker: Let Your Web App Feel Like a Native "
"Service Worker: Let Your Web App Feel Like a Native "
 
Svelte JS introduction
Svelte JS introductionSvelte JS introduction
Svelte JS introduction
 
Metrics by coda hale : to know your app’ health
Metrics by coda hale : to know your app’ healthMetrics by coda hale : to know your app’ health
Metrics by coda hale : to know your app’ health
 
Mobile Day - React Native
Mobile Day - React NativeMobile Day - React Native
Mobile Day - React Native
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testing
 
Academy PRO: React JS. Redux & Tooling
Academy PRO: React JS. Redux & ToolingAcademy PRO: React JS. Redux & Tooling
Academy PRO: React JS. Redux & Tooling
 
Workshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte IWorkshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte I
 
Javascript frameworks: Backbone.js
Javascript frameworks: Backbone.jsJavascript frameworks: Backbone.js
Javascript frameworks: Backbone.js
 
React JS and Redux
React JS and ReduxReact JS and Redux
React JS and Redux
 
React + Redux Introduction
React + Redux IntroductionReact + Redux Introduction
React + Redux Introduction
 
Protractor framework architecture with example
Protractor framework architecture with exampleProtractor framework architecture with example
Protractor framework architecture with example
 
Redux vs Alt
Redux vs AltRedux vs Alt
Redux vs Alt
 
Protocol Oriented MVVM - Auckland iOS Meetup
Protocol Oriented MVVM - Auckland iOS MeetupProtocol Oriented MVVM - Auckland iOS Meetup
Protocol Oriented MVVM - Auckland iOS Meetup
 

Andere mochten auch

CodeFest 2013. Прокопов Н. — Зачем вам нужна Clojure?
CodeFest 2013. Прокопов Н. — Зачем вам нужна Clojure?CodeFest 2013. Прокопов Н. — Зачем вам нужна Clojure?
CodeFest 2013. Прокопов Н. — Зачем вам нужна Clojure?
CodeFest
 
JavaScript завтра / Сергей Рубанов (Exante Limited)
JavaScript завтра / Сергей Рубанов  (Exante Limited)JavaScript завтра / Сергей Рубанов  (Exante Limited)
JavaScript завтра / Сергей Рубанов (Exante Limited)
Ontico
 

Andere mochten auch (20)

FlatGUI: Reactive GUI Toolkit Implemented in Clojure
FlatGUI: Reactive GUI Toolkit Implemented in ClojureFlatGUI: Reactive GUI Toolkit Implemented in Clojure
FlatGUI: Reactive GUI Toolkit Implemented in Clojure
 
Аренда класса
Аренда классаАренда класса
Аренда класса
 
Трансдюсеры, CSP каналы, неизменяемые структуры данных в JavaScript
Трансдюсеры, CSP каналы, неизменяемые структуры данных в JavaScriptТрансдюсеры, CSP каналы, неизменяемые структуры данных в JavaScript
Трансдюсеры, CSP каналы, неизменяемые структуры данных в JavaScript
 
Функциональное программирование в браузере / Никита Прокопов
Функциональное программирование в браузере / Никита ПрокоповФункциональное программирование в браузере / Никита Прокопов
Функциональное программирование в браузере / Никита Прокопов
 
CodeFest 2013. Прокопов Н. — Зачем вам нужна Clojure?
CodeFest 2013. Прокопов Н. — Зачем вам нужна Clojure?CodeFest 2013. Прокопов Н. — Зачем вам нужна Clojure?
CodeFest 2013. Прокопов Н. — Зачем вам нужна Clojure?
 
Построение мультисервисного стартапа в реалиях full-stack javascript
Построение мультисервисного стартапа в реалиях full-stack javascriptПостроение мультисервисного стартапа в реалиях full-stack javascript
Построение мультисервисного стартапа в реалиях full-stack javascript
 
2014.12.06 05 Антон Плешивцев — Разбираем естественные языки на Lisp'е
2014.12.06 05 Антон Плешивцев — Разбираем естественные языки на Lisp'е2014.12.06 05 Антон Плешивцев — Разбираем естественные языки на Lisp'е
2014.12.06 05 Антон Плешивцев — Разбираем естественные языки на Lisp'е
 
Назад в будущее! …и другие мысли о подготовке программистов в ВУЗах
Назад в будущее! …и другие мысли о подготовке программистов в ВУЗахНазад в будущее! …и другие мысли о подготовке программистов в ВУЗах
Назад в будущее! …и другие мысли о подготовке программистов в ВУЗах
 
JavaScript завтра / Сергей Рубанов (Exante Limited)
JavaScript завтра / Сергей Рубанов  (Exante Limited)JavaScript завтра / Сергей Рубанов  (Exante Limited)
JavaScript завтра / Сергей Рубанов (Exante Limited)
 
Hacking JavaFX with Groovy, Clojure, Scala, and Visage
Hacking JavaFX with Groovy, Clojure, Scala, and VisageHacking JavaFX with Groovy, Clojure, Scala, and Visage
Hacking JavaFX with Groovy, Clojure, Scala, and Visage
 
Алексей Романчук «Реактивное программирование»
Алексей Романчук «Реактивное программирование»Алексей Романчук «Реактивное программирование»
Алексей Романчук «Реактивное программирование»
 
Clojure - Why does it matter?
Clojure - Why does it matter?Clojure - Why does it matter?
Clojure - Why does it matter?
 
Some basic FP concepts
Some basic FP conceptsSome basic FP concepts
Some basic FP concepts
 
ClojureScript Introduction
ClojureScript IntroductionClojureScript Introduction
ClojureScript Introduction
 
Clojure+ClojureScript Webapps
Clojure+ClojureScript WebappsClojure+ClojureScript Webapps
Clojure+ClojureScript Webapps
 
Making design decisions in React-based ClojureScript web applications
Making design decisions in React-based ClojureScript web applicationsMaking design decisions in React-based ClojureScript web applications
Making design decisions in React-based ClojureScript web applications
 
ClojureScript - A functional Lisp for the browser
ClojureScript - A functional Lisp for the browserClojureScript - A functional Lisp for the browser
ClojureScript - A functional Lisp for the browser
 
"Content Security Policy" — Алексей Андросов, MoscowJS 18
"Content Security Policy" — Алексей Андросов, MoscowJS 18"Content Security Policy" — Алексей Андросов, MoscowJS 18
"Content Security Policy" — Алексей Андросов, MoscowJS 18
 
Monte carlo simulation
Monte carlo simulationMonte carlo simulation
Monte carlo simulation
 
Clojure #1
Clojure #1Clojure #1
Clojure #1
 

Ähnlich wie JavaFX GUI architecture with Clojure core.async

Developing your first application using FIWARE
Developing your first application using FIWAREDeveloping your first application using FIWARE
Developing your first application using FIWARE
FIWARE
 

Ähnlich wie JavaFX GUI architecture with Clojure core.async (20)

Highload JavaScript Framework without Inheritance
Highload JavaScript Framework without InheritanceHighload JavaScript Framework without Inheritance
Highload JavaScript Framework without Inheritance
 
Web services, WCF services and Multi Threading with Windows Forms
Web services, WCF services and Multi Threading with Windows FormsWeb services, WCF services and Multi Threading with Windows Forms
Web services, WCF services and Multi Threading with Windows Forms
 
Jsf2 html5-jazoon
Jsf2 html5-jazoonJsf2 html5-jazoon
Jsf2 html5-jazoon
 
Java Web Programming on Google Cloud Platform [3/3] : Google Web Toolkit
Java Web Programming on Google Cloud Platform [3/3] : Google Web ToolkitJava Web Programming on Google Cloud Platform [3/3] : Google Web Toolkit
Java Web Programming on Google Cloud Platform [3/3] : Google Web Toolkit
 
GWT
GWTGWT
GWT
 
Google Web Toolkit
Google Web ToolkitGoogle Web Toolkit
Google Web Toolkit
 
The fundamental problems of GUI applications and why people choose React
The fundamental problems of GUI applications and why people choose ReactThe fundamental problems of GUI applications and why people choose React
The fundamental problems of GUI applications and why people choose React
 
Architectural Patterns and Software Architectures: Client-Server, Multi-Tier,...
Architectural Patterns and Software Architectures: Client-Server, Multi-Tier,...Architectural Patterns and Software Architectures: Client-Server, Multi-Tier,...
Architectural Patterns and Software Architectures: Client-Server, Multi-Tier,...
 
Jsf presentation
Jsf presentationJsf presentation
Jsf presentation
 
Windows 8 for Web Developers
Windows 8 for Web DevelopersWindows 8 for Web Developers
Windows 8 for Web Developers
 
Java Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAXJava Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAX
 
Html5
Html5Html5
Html5
 
Airflow presentation
Airflow presentationAirflow presentation
Airflow presentation
 
Developing maintainable Cordova applications
Developing maintainable Cordova applicationsDeveloping maintainable Cordova applications
Developing maintainable Cordova applications
 
When Web Services Go Bad
When Web Services Go BadWhen Web Services Go Bad
When Web Services Go Bad
 
using Mithril.js + postgREST to build and consume API's
using Mithril.js + postgREST to build and consume API'susing Mithril.js + postgREST to build and consume API's
using Mithril.js + postgREST to build and consume API's
 
Web Performance Part 4 "Client-side performance"
Web Performance Part 4  "Client-side performance"Web Performance Part 4  "Client-side performance"
Web Performance Part 4 "Client-side performance"
 
Developing your first application using FIWARE
Developing your first application using FIWAREDeveloping your first application using FIWARE
Developing your first application using FIWARE
 
MOPCON 2014 - Best software architecture in app development
MOPCON 2014 - Best software architecture in app developmentMOPCON 2014 - Best software architecture in app development
MOPCON 2014 - Best software architecture in app development
 
Democratizing Serverless
Democratizing ServerlessDemocratizing Serverless
Democratizing Serverless
 

Kürzlich hochgeladen

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 

Kürzlich hochgeladen (20)

WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 

JavaFX GUI architecture with Clojure core.async

  • 1. JavaFX GUI architecture with Clojure core.async @friemens
  • 2.
  • 4. GUI implementation causes significant LOC numbers
  • 6. Automatic GUI testing is expensive
  • 7. GUI code needs a suitable architecture
  • 9. Model Controller View MVC makes you think of mutable things
  • 10. MVC Variations MVP a.k.a Passive View View Model Presenter View Model View Model MVVM a.k.a PresentationModel
  • 11. A real-world OO GUI architecture ControllerViewModel ViewImpl UI Toolkit Impl UIView Other parts of the system two-way databinding updates action events only data!
  • 12. Benefits so far ControllerViewModel ViewImpl UI Toolkit Impl UIView Other parts of the system two-way databinding updates action events only data! Dumb Views => generated code Dumb ViewModels => generated code Controllers are unit-testable
  • 13. Remaining annoyances ControllerViewModel ViewImpl UI Toolkit Impl UIView Other parts of the system two-way databinding updates action events only data! Unpredicatble execution paths Coordination with long runnning code Merging of responses into ViewModels Window modality is based on a hack
  • 14. Think again... what is a user interface?
  • 15. events state 1) is a representation of system state A user interface ... {:name {:value "Foo" :message nil} :addresses [{:name "Bar" :street "Barstr" :city "Berlin"} {:name "Baz" :street "Downstr" :city "Bonn"}] :selected [1]}
  • 16. events state 1) is a representation of system state 2) allows us to transform system state A user interface ... {:name {:value "Foo" :message nil} :addresses [{:name "Bar" :street "Barstr" :city "Berlin"} {:name "Baz" :street "Downstr" :city "Bonn"}] :selected [1]} 2) 1)
  • 17. A user interface ... … consists of two functions ... which – for technical reasons – need to be executed asynchronously. [state] → ⊥ ;; update UI (side effects!) [state event] → state ;; presentation logic ( )
  • 19. GUI can become unresponsive Java FX application thread Event loop Your code Service call What happens if a service call takes seconds?
  • 20. Keep GUI responsive (callback based solution) Service call Your code 1 Your code 2 Use other thread Java FX application thread Event loop Some worker thread Delegate execution Schedule to event loop
  • 21. Meet core.async: channels go blocks+ Based on Tony Hoare's CSP* approach (1978). Communicating Sequential Processes * (require '[clojure.core.async :refer [put! >! <! go chan go-loop]]) (def c1 (chan)) (go-loop [xs []] (let [x (<! c1)] (println "Got" x ", xs so far:" xs) (recur (conj xs x)))) (put! c1 "foo") ;; outputs: Got bar , xs so far: [foo] a blocking read make a new channelcreates a lightweight process async write readwrite
  • 22. The magic of go sequential code in go block read write macro expansion state machine code snippets
  • 23. Keep GUI responsive (CSP based solution) core.async process core.async process Java FX application thread Your code Update UI <! >! <! put! go-loop one per viewexactly one events state
  • 24. Expensive service call: it's your choice (def events (chan)) (go-loop [] (let [evt (<! events)] (case ((juxt :type :value) evt) [:action :invoke-blocking] (case (-> (<! (let [ch (chan)] (future (put! ch (expensive-service-call))) ch)) :state) :ok (println "(sync) OK") :nok (println "(sync) Error")) [:action :invoke-non-blocking] (future (put! events {:type :call :value (-> (expensive-service-call) :state)})) [:call :ok] (println "(async) OK") [:call :nok] (println "(async) Error"))) (recur)) blocking non- blocking ad-hoc new channel use views events channel
  • 25. Properties of CSP based solution „Blocking read“ expresses modality A views events channel takes ALL async results ✔ long-running calculations ✔ service calls ✔ results of other views Each view is an async process Strong separation of concerns
  • 27. JavaFX + Tk-process + many view-processes JavaFX Many view processes One toolkit oriented process (run-view) (run-tk) Event handler (spec) (handler) Each view has one events channel
  • 28. Data representing view state :id ;; identifier :spec ;; data describing visual components :vc ;; instantiated JavaFX objects :data ;; user data :mapping ;; mapping user data <-> VCs :events ;; core.async channel :setter-fns ;; map of update functions :validation-rule-set ;; validation rules :validation-results ;; current validation messages :terminated ;; window can be closed :cancelled ;; abandon user data
  • 29. (spec) - View specification with data (defn item-editor-spec [data] (-> (v/make-view "item-editor" (window "Item Editor" :modality :window :content (panel "Content" :lygeneral "wrap 2, fill" :lycolumns "[|100,grow]" :components [(label "Text") (textfield "text" :lyhint "growx") (panel "Actions" :lygeneral "ins 0" :lyhint "span, right" :components [(button "OK") (button "Cancel")])]))) (assoc :mapping (v/make-mapping :text ["text" :text]) :validation-rule-set (e/rule-set :text (c/min-length 1)) :data data))) attach more configuration data a map with initial user data specify contents
  • 30. (handler) - Event handler of a view (defn item-editor-handler [view event] (go (case ((juxt :source :type) event) ["OK" :action] (assoc view :terminated true) ["Cancel" :action] (assoc view :terminated true :cancelled true) view)))
  • 31. Using a view (let [editor-view (<! (v/run-view #'item-editor-spec #'item-editor-handler {:text (nth items index)}))] . . .) (defn item-editor-spec [data] (-> (v/make-view "item-editor" (window "Item Editor" :modality :window :content (panel "Content" :lygeneral "wrap 2, fill" :lycolumns "[|100,grow]" :components [(label "Text") (textfield "text":lyhint "growx") (panel "Actions" :lygeneral "ins 0" :lyhint "span, right" :components [(button "OK") (button "Cancel")])]))) (assoc :mapping (v/make-mapping :text ["text" :text]) :validation-rule-set (e/rule-set :text (c/min-length 1)) :data data))) (defn item-editor-handler [view event] (go (case ((juxt :source :type) event) ["OK" :action] (assoc view :terminated true) ["Cancel" :action] (assoc view :terminated true :cancelled true) view))) a map with initial user data spec handler calling view process waits for callee
  • 32. You can easily build it yourself! JavaFX API update build Toolkit Impl View process fns Toolkit process fns core.clj tk.clj builder.clj binding.clj bind < 400 LOC
  • 34. MVC leads to thinking in terms of mutation UIs introduce asynchronity UI is a reactive representation of system state
  • 35. Thank you for listening! Questions? @friemens www.itemis.de@itemis https://github.com/friemen/async-ui