SlideShare uma empresa Scribd logo
1 de 35
Baixar para ler offline
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

Mais conteúdo relacionado

Mais procurados

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
 

Mais procurados (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
 

Destaque

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
 

Destaque (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
 

Semelhante a 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
 

Semelhante a 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
 

Último

Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 

Último (20)

Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 

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