RxJava and SWT: Out with Events, in with FRP

Slides:



Advertisements
Similar presentations
Introduction to Macromedia Director 8.5 – Lingo
Advertisements

Introduction to Eclipse. Start Eclipse Click and then click Eclipse from the menu: Or open a shell and type eclipse after the prompt.
Chapter 16 Exception Handling. What is Exception Handling? A method of handling errors that informs the user of the problem and prevents the program from.
An Introduction to the Reactive Extensions Ivan Towlson Mindscape.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
Delegates & Events Observer and Strategy Patterns Game Design Experience Professor Jim Whitehead January 30, 2009 Creative Commons Attribution 3.0 creativecommons.org/licenses/by/3.0.
Cosc 4755 Phone programming: GUI Concepts & Threads.
What is AML? What is a program? What is AML? An AML can: –Automate frequently performed actions –Provide a quick and consistent way to set environments.
COMP 5138 Relational Database Management Systems Semester 2, 2007 Lecture 8A Transaction Concept.
Exception Error handling. Exception 4 n An unusual occurrence during program execution that requires immediate handling n Errors are the most common type.
SE320: Introduction to Computer Games Week 8: Game Programming Gazihan Alankus.
Options for User Input Options for getting information from the user –Write event-driven code Con: requires a significant amount of new code to set-up.
Event Handling in Java: Alternatives and Patterns Raja Sooriamurthi Information Systems Department Kelley School of Business Indiana.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
Designing For Testability. Incorporate design features that facilitate testing Include features to: –Support test automation at all levels (unit, integration,
Reactive Extensions Ye olde introduction and walk-through, with plenty o’ code.
Bill's Amazing Content Rotator jQuery Content Rotator.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 13: An Introduction to C++
Reactive Extensions (Rx) Explained Presenter: Kevin Grossnicklaus August 5 th, 2011.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 3.
Java Threads. What is a Thread? A thread can be loosely defined as a separate stream of execution that takes place simultaneously with and independently.
Digital Electronics and Computer Interfacing Tim Mewes 4. LabVIEW - Advanced.
Applications Development
IBM TSpaces Lab 3 Transactions Event Registration.
CSE 331 Software Design & Implementation Hal Perkins Autumn 2012 Event-Driven Programming 1.
Advanced Concurrency Topics Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
JavaScript, Fourth Edition
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
JQuery JavaScript is a powerful language but it is not always easy to work with. jQuery is a JavaScript library that helps with: – HTML document traversal.
Android Threads. Threads Android will show an “ANR” error if a View does not return from handling an event within 5 seconds Or, if some code running in.
Introduction to Computing Concepts Note Set 15. JOptionPane.showMessageDialog Message Dialog Allows you to give a brief message to the user Can be used.
ITIP © Ron Poet Lecture 14 1 Responsibilities. ITIP © Ron Poet Lecture 14 2 Two Sections of Code  If we ask two people to work together to do a job,
Thinking reactive. Who is speaking? Software developer at Seavus Member of JugMK coffee - code - pizza - repeat.
Functions.  Assignment #2 is now due on Wednesday, Nov 25 th  (No Quiz)  Go over the midterm  Backtrack and re-cover the question about tracing the.
John Maver (978)
Continuous. Flow of Control Programs can broadly be classified as being –Procedural Programs are executed once in the order specified by the code varied.
Clean Code “Keep it Clean, Your Mother Doesn’t Work Here”“Keep it Clean, Your Mother Doesn’t Work Here” William PenberthyWilliam Penberthy Application.
Aquarium Lab Series Developed by Alyce BradyAlyce Brady of Kalamazoo CollegeKalamazoo College.
1 Why Threads are a Bad Idea (for most purposes) based on a presentation by John Ousterhout Sun Microsystems Laboratories Threads!
1 Project 7: Looping. Project 7 For this project you will produce two Java programs. The requirements for each program will be described separately on.
IMS 3253: Validation and Errors 1 Dr. Lawrence West, MIS Dept., University of Central Florida Topics Validation and Error Handling Validation.
RxJava and SWT: Out with Events, in with FRP Ned Twigg All code examples available here.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
Integrating and Extending Workflow 8 AA301 Carl Sykes Ed Heaney.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
Coming up Implementation vs. Interface The Truth about variables Comparing strings HashMaps.
Java Exceptions a quick review….
Introduction to Event-Driven Programming
Advanced Topics in Concurrency and Reactive Programming: Asynchronous Programming Majeed Kassis.
Advanced Topics in Concurrency and Reactive Programming: The Observable Contract Majeed Kassis.
Mobile Applications (Android Programming)
Delegates and Events 14: Delegates and Events
CSE 331 Software Design and Implementation
Introduction to Events
Scaling of Eclipse on High Density Displays
Angularjs Interview Questions and Answers By Hope Tutors.
PC02 Term 1 Project Basic Messenger. PC02 Term 1 Project Basic Messenger.
Phil Tayco Slide version 1.0 Created Oct 2, 2017
Advanced Topics in Concurrency and Reactive Programming: ReactiveX
Switch Statements, Do While, Break, Continue, Goto, Comma Operator
CSE 331 Software Design and Implementation
We’re moving on to more recap from other programming languages
Android Topics UI Thread and Limited processing resources
Android Topics Asynchronous Callsbacks
WPS - your story so far Seems incredible complicated, already
…and web frameworks in general
Tonga Institute of Higher Education
CSE 1020:Software Development
Rx Java intro Vaidas Kriščeliūnas.
Server & Tools Business
Presentation transcript:

RxJava and SWT: Out with Events, in with FRP Ned Twigg Twitter @nedtwigg All code examples available here https://github.com/diffplug/rxjava_and_swt

What is Functional Reactive Programming A buzzword for event-driven programming Except the events live inside a pipe that models time explicitly Epigrams in Programming #9 (Alan Perlis 1988, 30-50 years of experience) It is better to have 100 functions operate on one data structure than 10 functions on 10 data structures. SWT – ~30 event / listener pairs, 0 methods RxJava – 1 event / listener pair, gazillion methods

What makes RxJava more “composable”? In SWT, we add an event handler like this: In RxJava, we add an event handler like this: Observable is a pipe we can filter, map, and more! widget.addListener(SWT.KeyDown, e -> { // this is our chance to react System.out.println("keyCode=" + e.keyCode); }); Observable<Event> keyDownStream = SwtRx.addListener(widget, SWT.KeyDown); keyDownStream.subscribe(e -> { // this is our chance to react System.out.println("keyCode=" + e.keyCode); });

What is an “Observable” public interface Observer<T> { void onNext(T t); void onComplete(); void onError(Throwable e); } You can subscribe an Observer<T> with these methods:

What good is a pipe? Event callbacks and event streams are the same every if statement = filter every new value = map A keypress will cause a cascade of actions across your program With Events, that cascade flows through ad-hoc function calls With Observables, that cascade is explicitly modeled and comes with batteries Especially for time – debounce, sample, throttle, etc. if (e.keyCode == 'q') { System.out.println("user wants to leave talk"); } keyDownStream.filter(e -> e.keyCode == 'q').subscribe(e -> { System.out.println("user wants to leave talk"); }); int accel = e.keyCode | e.stateMask; String keyPress = Actions.getAcceleratorString(accel); System.out.println(keyPress); keyDownStream.map(e -> e.keyCode | e.stateMask).subscribe(accel -> { System.out.println(Actions.getAcceleratorString(accel)); });

Events – nested calls Observable – decouples the event’s source from its effects

Just a smidge harder… Events – nested calls Observable – decouples the event’s source from its effects

Xkcd Color Survey Show the user a random RGB value Ask them to name it Take all the RGB values that were labeled with the same name and average them to find the “truest” red, green, vomit green, etc.

Given an RGB value, what is the nearest named RGB value? CompletionStage<Map.Entry<String, RGB>> getNearestColor(RGB rgb) How do we make this work?

Create yet another event pair RxJava Expose SWT Listeners /** Adds the given listener to the color canvas. */ void addListener(int eventType, Listener listener); /** Converts a coordinate to an RGB value. */ RGB toColor(int x, int y); Create yet another event pair RxJava public class ColorEvent { RGB color; } public interface ColorListener { void handle(ColorEvent event); void addMouseMoveListener(ColorListener listener); void addMouseDownListener(ColorListener listener); Observable<RGB> rxMouseMove(); Observable<RGB> rxMouseDown();

Passing errors (that you thought of) Either<Value, Throwable>

Handling errors (that you didn’t think of) Async code makes it easy to swallow errors It’s a big problem with Observables and Futures Too easy to subscribe to values, and forget to subscribe to errors Current behavior is “swallow by default” Log by default is much better…

Some useful libraries Durian – no deps Box -> a value you can get() and set() Either DurianRx – requires Durian and Guava (but we’re removing Guava) RxBox -> a value you can get(), set(), and subscribe to Rx.subscribe(Observable/CompletionStage/ListenableFuture) DurianSwt – requires the above and SWT / JFace SwtRx.addListener() SwtExec.async().subscribe() InteractiveTest.testCmp()

Mapping Futures to Observables A future returns either a value or an exception Value -> onValue(), onCompleted() Exception -> onError() It makes sense to use the same subscription and error-handling policies for all async code. Rx.subscribe(Future or Observable, onValue -> doSomething()); Automatically logs all exceptions. If you set a magic system property, it will record the stacktrace at the time of subscription, and decorate any exceptions with their source durian.plugins.com.diffplug.common.rx.RxTracingPolicy=com.diffplug.common.rx.Rx TracingPolicy$LogSubscriptionTrace

SWT Threads SwtExec.async() -> Display.asyncExec() SwtExec.blocking() -> Display.syncExec() SwtExec.immediate() SwtExec.async().guardOn(control).subscribe(Observable, Callback) public void execute(Runnable runnable) { if (Thread.currentThread() == display.getThread()) { runnable.run(); } else { display.asyncExec(runnable); }

InteractiveTest Ideally, all UI is tested with UI automation. Practically, most UIs don’t have tests and are buggy. Middle ground is a user-in-the-loop test suite, which can run on a headless server to make sure the tests still work for the user. gradlew interactiveTest - runs interactive tests and prompts user gradlew headlessTest - runs interactive tests for 500ms each

- 1 + 1 Evaluate the Sessions Sign in and vote at eclipsecon.org Code available at diffplug.com/opensource Get updates by following @diffplug Evaluate the Sessions Sign in and vote at eclipsecon.org - 1 + 1