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?

React Native: JS MVC Meetup #15
React Native: JS MVC Meetup #15React Native: JS MVC Meetup #15
React Native: JS MVC Meetup #15Rob Gietema
 
MBLTDev15: Egor Tolstoy, Rambler&Co
MBLTDev15: Egor Tolstoy, Rambler&CoMBLTDev15: Egor Tolstoy, Rambler&Co
MBLTDev15: Egor Tolstoy, Rambler&Coe-Legion
 
Groovy Ecosystem - JFokus 2011 - Guillaume Laforge
Groovy Ecosystem - JFokus 2011 - Guillaume LaforgeGroovy Ecosystem - JFokus 2011 - Guillaume Laforge
Groovy Ecosystem - JFokus 2011 - Guillaume LaforgeGuillaume Laforge
 
Reactive, component 그리고 angular2
Reactive, component 그리고  angular2Reactive, component 그리고  angular2
Reactive, component 그리고 angular2Jeado Ko
 
Unity and WebSockets
Unity and WebSocketsUnity and WebSockets
Unity and WebSocketsJosh Glover
 
Load testing with gatling
Load testing with gatlingLoad testing with gatling
Load testing with gatlingChris Birchall
 
"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 "FDConf
 
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’ healthIzzet Mustafaiev
 
Mobile Day - React Native
Mobile Day - React NativeMobile Day - React Native
Mobile Day - React NativeSoftware Guru
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingVisual Engineering
 
Academy PRO: React JS. Redux & Tooling
Academy PRO: React JS. Redux & ToolingAcademy PRO: React JS. Redux & Tooling
Academy PRO: React JS. Redux & ToolingBinary Studio
 
Workshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte IWorkshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte IVisual Engineering
 
Javascript frameworks: Backbone.js
Javascript frameworks: Backbone.jsJavascript frameworks: Backbone.js
Javascript frameworks: Backbone.jsSoós Gábor
 
React JS and Redux
React JS and ReduxReact JS and Redux
React JS and ReduxGlib Kechyn
 
React + Redux Introduction
React + Redux IntroductionReact + Redux Introduction
React + Redux IntroductionNikolaus Graf
 
Protractor framework architecture with example
Protractor framework architecture with exampleProtractor framework architecture with example
Protractor framework architecture with exampleshadabgilani
 
Protocol Oriented MVVM - Auckland iOS Meetup
Protocol Oriented MVVM - Auckland iOS MeetupProtocol Oriented MVVM - Auckland iOS Meetup
Protocol Oriented MVVM - Auckland iOS MeetupNatasha Murashev
 

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

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 Clojuredenyslebediev
 
Трансдюсеры, CSP каналы, неизменяемые структуры данных в JavaScript
Трансдюсеры, CSP каналы, неизменяемые структуры данных в JavaScriptТрансдюсеры, CSP каналы, неизменяемые структуры данных в JavaScript
Трансдюсеры, CSP каналы, неизменяемые структуры данных в JavaScriptMax Klymyshyn
 
Функциональное программирование в браузере / Никита Прокопов
Функциональное программирование в браузере / Никита ПрокоповФункциональное программирование в браузере / Никита Прокопов
Функциональное программирование в браузере / Никита ПрокоповOntico
 
CodeFest 2013. Прокопов Н. — Зачем вам нужна Clojure?
CodeFest 2013. Прокопов Н. — Зачем вам нужна Clojure?CodeFest 2013. Прокопов Н. — Зачем вам нужна Clojure?
CodeFest 2013. Прокопов Н. — Зачем вам нужна Clojure?CodeFest
 
Построение мультисервисного стартапа в реалиях full-stack javascript
Построение мультисервисного стартапа в реалиях full-stack javascriptПостроение мультисервисного стартапа в реалиях full-stack javascript
Построение мультисервисного стартапа в реалиях full-stack javascriptFDConf
 
2014.12.06 05 Антон Плешивцев — Разбираем естественные языки на Lisp'е
2014.12.06 05 Антон Плешивцев — Разбираем естественные языки на Lisp'е2014.12.06 05 Антон Плешивцев — Разбираем естественные языки на Lisp'е
2014.12.06 05 Антон Плешивцев — Разбираем естественные языки на Lisp'еHappyDev
 
Назад в будущее! …и другие мысли о подготовке программистов в ВУЗах
Назад в будущее! …и другие мысли о подготовке программистов в ВУЗахНазад в будущее! …и другие мысли о подготовке программистов в ВУЗах
Назад в будущее! …и другие мысли о подготовке программистов в ВУЗахDennis Schetinin
 
JavaScript завтра / Сергей Рубанов (Exante Limited)
JavaScript завтра / Сергей Рубанов  (Exante Limited)JavaScript завтра / Сергей Рубанов  (Exante Limited)
JavaScript завтра / Сергей Рубанов (Exante Limited)Ontico
 
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 VisageStephen Chin
 
Алексей Романчук «Реактивное программирование»
Алексей Романчук «Реактивное программирование»Алексей Романчук «Реактивное программирование»
Алексей Романчук «Реактивное программирование»DevDay
 
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 applicationsFalko Riemenschneider
 
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 browserFalko Riemenschneider
 
"Content Security Policy" — Алексей Андросов, MoscowJS 18
"Content Security Policy" — Алексей Андросов, MoscowJS 18"Content Security Policy" — Алексей Андросов, MoscowJS 18
"Content Security Policy" — Алексей Андросов, MoscowJS 18MoscowJS
 
Monte carlo simulation
Monte carlo simulationMonte carlo simulation
Monte carlo simulationAnurag Jaiswal
 

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

Highload JavaScript Framework without Inheritance
Highload JavaScript Framework without InheritanceHighload JavaScript Framework without Inheritance
Highload JavaScript Framework without InheritanceFDConf
 
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 FormsPeter Gfader
 
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 ToolkitIMC Institute
 
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 ReactOliver N
 
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,...Svetlin Nakov
 
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 AJAXIMC Institute
 
Airflow presentation
Airflow presentationAirflow presentation
Airflow presentationIlias Okacha
 
Developing maintainable Cordova applications
Developing maintainable Cordova applicationsDeveloping maintainable Cordova applications
Developing maintainable Cordova applicationsIvano Malavolta
 
When Web Services Go Bad
When Web Services Go BadWhen Web Services Go Bad
When Web Services Go BadSteve Loughran
 
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'sAntônio Roberto Silva
 
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"Binary Studio
 
Developing your first application using FIWARE
Developing your first application using FIWAREDeveloping your first application using FIWARE
Developing your first application using FIWAREFIWARE
 
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 developmentanistar sung
 
Democratizing Serverless
Democratizing ServerlessDemocratizing Serverless
Democratizing ServerlessShaun Smith
 

Ä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

Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 

Kürzlich hochgeladen (20)

Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 

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