1 Reactive Programming with Rx (based on Ras Bodik, Thibaud Hottelier, James Ide UC Berkeley CS164: Introduction.

Slides:



Advertisements
Similar presentations
2. Getting Started Heejin Park College of Information and Communications Hanyang University.
Advertisements

Zhongxing Telecom Pakistan (Pvt.) Ltd
1
1 Vorlesung Informatik 2 Algorithmen und Datenstrukturen (Parallel Algorithms) Robin Pomplun.
1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 2 Getting Started.
© 2008 Pearson Addison Wesley. All rights reserved Chapter Seven Costs.
Copyright © 2003 Pearson Education, Inc. Slide 1 Computer Systems Organization & Architecture Chapters 8-12 John D. Carpinelli.
Copyright © 2003 Pearson Education, Inc. Slide 7-1 Created by Cheryl M. Hughes The Web Wizards Guide to XML by Cheryl M. Hughes.
Processes and Operating Systems
Copyright © 2011, Elsevier Inc. All rights reserved. Chapter 6 Author: Julia Richards and R. Scott Hawley.
Author: Julia Richards and R. Scott Hawley
1 Copyright © 2013 Elsevier Inc. All rights reserved. Appendix 01.
Properties Use, share, or modify this drill on mathematic properties. There is too much material for a single class, so you’ll have to select for your.
UNITED NATIONS Shipment Details Report – January 2006.
RXQ Customer Enrollment Using a Registration Agent (RA) Process Flow Diagram (Move-In) Customer Supplier Customer authorizes Enrollment ( )
Document #07-2I RXQ Customer Enrollment Using a Registration Agent (RA) Process Flow Diagram (Move-In) (mod 7/25 & clean-up 8/20) Customer Supplier.
1 Hyades Command Routing Message flow and data translation.
Business Transaction Management Software for Application Coordination 1 Business Processes and Coordination. Introduction to the Business.
18 Copyright © 2005, Oracle. All rights reserved. Distributing Modular Applications: Introduction to Web Services.
15 Copyright © 2005, Oracle. All rights reserved. Adding User Interface Components and Event Handling.
We need a common denominator to add these fractions.
FIGURE 8.1 Process and controller.
1 RA I Sub-Regional Training Seminar on CLIMAT&CLIMAT TEMP Reporting Casablanca, Morocco, 20 – 22 December 2005 Status of observing programmes in RA I.
Properties of Real Numbers CommutativeAssociativeDistributive Identity + × Inverse + ×
Custom Statutory Programs Chapter 3. Customary Statutory Programs and Titles 3-2 Objectives Add Local Statutory Programs Create Customer Application For.
FACTORING ax2 + bx + c Think “unfoil” Work down, Show all steps.
Mike Scott University of Texas at Austin
1 Click here to End Presentation Software: Installation and Updates Internet Download CD release NACIS Updates.
Solve Multi-step Equations
REVIEW: Arthropod ID. 1. Name the subphylum. 2. Name the subphylum. 3. Name the order.
Week 2 The Object-Oriented Approach to Requirements
Turing Machines.
PP Test Review Sections 6-1 to 6-6
Campaign Overview Mailers Mailing Lists
EU market situation for eggs and poultry Management Committee 20 October 2011.
EIS Bridge Tool and Staging Tables September 1, 2009 Instructor: Way Poteat Slide: 1.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 24.1 Test-Driving the Ticket Information Application.
XML and Databases Exercise Session 3 (courtesy of Ghislain Fourny/ETH)
Green Eggs and Ham.
1 What is JavaScript? JavaScript was designed to add interactivity to HTML pages JavaScript is a scripting language A scripting language is a lightweight.
Exarte Bezoek aan de Mediacampus Bachelor in de grafische en digitale media April 2014.
How to convert a left linear grammar to a right linear grammar
Copyright © 2012, Elsevier Inc. All rights Reserved. 1 Chapter 7 Modeling Structure with Blocks.
1 RA III - Regional Training Seminar on CLIMAT&CLIMAT TEMP Reporting Buenos Aires, Argentina, 25 – 27 October 2006 Status of observing programmes in RA.
Factor P 16 8(8-5ab) 4(d² + 4) 3rs(2r – s) 15cd(1 + 2cd) 8(4a² + 3b²)
Basel-ICU-Journal Challenge18/20/ Basel-ICU-Journal Challenge8/20/2014.
1..
CONTROL VISION Set-up. Step 1 Step 2 Step 3 Step 5 Step 4.
© 2012 National Heart Foundation of Australia. Slide 2.
Adding Up In Chunks.
CS 240 Computer Programming 1
Model and Relationships 6 M 1 M M M M M M M M M M M M M M M M
1 hi at no doifpi me be go we of at be do go hi if me no of pi we Inorder Traversal Inorder traversal. n Visit the left subtree. n Visit the node. n Visit.
Analyzing Genes and Genomes
Chapter 9 Interactive Multimedia Authoring with Flash Introduction to Programming 1.
Types of selection structures
©Brooks/Cole, 2001 Chapter 12 Derived Types-- Enumerated, Structure and Union.
Chapter 12 Working with Forms Principles of Web Design, 4 th Edition.
Essential Cell Biology
Intracellular Compartments and Transport
PSSA Preparation.
Essential Cell Biology
Immunobiology: The Immune System in Health & Disease Sixth Edition
Energy Generation in Mitochondria and Chlorplasts
Introduction Peter Dolog dolog [at] cs [dot] aau [dot] dk Intelligent Web and Information Systems September 9, 2010.
TCP/IP Protocol Suite 1 Chapter 18 Upon completion you will be able to: Remote Login: Telnet Understand how TELNET works Understand the role of NVT in.

1 Lecture 21 Reactive Programming with Rx Duality between Push and Pull models, Iterable vs. Observable. Composing two asynchronous services. Ras Bodik.
1 Lecture 22 Reactive Programming with Rx Duality between Push and Pull models, Iterable vs. Observable. Composing two asynchronous services. Ras Bodik.
Presentation transcript:

1 Reactive Programming with Rx (based on Ras Bodik, Thibaud Hottelier, James Ide UC Berkeley CS164: Introduction to Programming Languages and Compilers Fall 2010

Iterable vs Observable Iterable: sequence I can iterate over and pull values Observable: sequence that notifies when a new value is added (push) These two are dual 2

1) Observable and Observer objects Data source: var answer = Rx.Observable.Return(42); Listener: var observer = Rx.Observer.Create( function (x) { document.write("The answer is " + x); } ); Connecting the two: answer.Subscribe(observer); 3

The same code packaged in a web page function iExploreRx() { var answer = Rx.Observable.Return(42); var observer = Rx.Observer.Create( function (x) { document.write("The answer is " + x); } ); answer.Subscribe(observer); } Tell me the answer 4

2) Observable sequences First, let’s set up the listener: var source = null; // we’ll try various sequences here var subscription = source.Subscribe( function (next) { $(" ").html("OnNext: "+next).appendTo("#content"); }, function (exn) { $(" ").html("OnError: "+exn).appendTo("#content"); }, function () { $(" ").html("OnCompleted").appendTo("#content"); }); 5

Empty sequence var source = Rx.Observable.Empty(); Produces the output OnCompleted 6

Sequence with a terminating notification var source = Rx.Observable.Throw("Oops!"); Running this code produces the following output: OnError: Oops 7

Single-element sequence var source = Rx.Observable.Return(42); Running this code produces the following output: OnNext: 42 OnCompleted 8

We are now done with trivial sequences var source = Rx.Observable.Range(5, 3); Running this code produces the following output: OnNext: 5 OnNext: 6 OnNext: 7 OnCompleted 9

A for-loop like sequence generator var source = Rx.Observable.GenerateWithTime( 0, // initial value of iterator variable function(i) { return i < 5; }, // test function(i) { return i + 1; }, // incr function(i) { return i * i; }, // value function(i) { return i * 1000; } ); Last function computes how many ms to wait between generated values (here, 1, 2, 3, … seconds) 10

3) Events as data sources In JavaScript $(document).ready(function () { $(document).mousemove(function (event) { $(" ").text("X: " + event.pageX+" Y: " + event.pageY).appendTo("#content"); }); In Rx $(document).ready(function () { $(document).toObservable("mousemove").Subscribe(function(event){ $(" ").text("X: " + event.pageX+" Y: " + event.pageY).appendTo("#content"); }); 11

4) Projection and filtering In event-handler programming, you’d write: function handleMouseMove(event) { // FILTER some events if (event.pageX === event.pageY) { // Only respond to events for mouse moves // over the first bisector of the page. } function handleKeyUp(event) { // PROJECT the event’s val var text = $(event.target).val(); // And now we can forget about the rest // of the event object’s data... } 12

The same in Rx var moves = $(document).toObservable("mousemove").Select(function(event) { return { pageX : event.pageX, pageY : event.pageY }; }); var input = $("#textbox").toObservable("keyup").Select(function(event) { return $(event.target).val(); }); 13

Now we can subscribe to moves and input var movesSubscription = moves.Subscribe(function (pos) { $(" ").text("X: " + pos.pageX + " Y: " + pos.pageY).appendTo("#content"); }); var inputSubscription = input.Subscribe(function (text) { $(" ").text("User wrote: " + text).appendTo("#content"); }); 14

Composition We were able to compose observable sequences thanks to the first-class nature of sequences “First-class” means sequences are values which can be stores, passed, and we can define operators for them, such as the filter operator Where. 15

Removing duplicate events DOM raises a keyup event even when the text in textbox does not change. For example, if you select a letter and change it to the same letter. This causes duplicate events: 16

Rx solution var input = $("#textbox").toObservable("keyup").Select(function (event) { return $(event.target).val();}).DistinctUntilChanged(); var inputSubscription = input.Subscribe(function (text) { $(" ").text("User wrote: " + text).appendTo("#content"); }); 17

Do, Throttle, and Timestamp var input = $("#textbox").toObservable("keyup").Select(function (event) { return $(event.target).val(); }).Timestamp().Do(function(inp) { var text = "I: " + inp.Timestamp + "-" + inp.Value; $(" ").text(text).appendTo("#content"); }).RemoveTimestamp().Throttle(1000).Timestamp().Do(function(inp) { var text = "T: " + inp.Timestamp + "-" + inp.Value; $(" ").text(text).appendTo("#content"); }).RemoveTimestamp().DistinctUntilChanged(); 18

Throttle A timer is used to let an incoming message age for the specified duration, after which it can be propagated further on. If during this timeframe another message comes in, the original message gets dropped on the floor and substituted for the new one that effectively also resets the timer. Can be used to suppress the number of requests sent to a web service. 19

6) Asynchrony with the server Let’s implement instant search for Wikipedia: 20

Interface to Wikipedia in JS 21 $.ajax({ url: " dataType: "jsonp", data: { action: "opensearch", search: "react", format: "json" }, success: function (data, textStatus, xhr) { $("#results").empty(); $.each(data[1], function (_, result) { $("#results").append(" " + result+" "); }); }, error: function (xhr, textStatus, errorThrown) { $("#error").text(errorThrown); } });

The same in Rx $.ajaxAsObservable( { url: " dataType: "jsonp", data: { action: "opensearch", search: "react", format: "json" } }); 22

From a term to observable with search results A function that creates an observable for a search term: function searchWikipedia(term) { return $.ajaxAsObservable( { url: " dataType: "jsonp", data: { action: "opensearch", search: term, format: "json" } }).Select(function (d) { return d.data[1]; }); } 23

Print the result of the search var searchObservable = searchWikipedia("react"); var searchSubscription = searchObservable.Subscribe( function (results) { $("#results").empty(); $.each(results, function (_, result) { $("#results").append(" "+result+" "); }); }, function (exn) { $("#error").text(error); } ); 24

7) The full thing (dealing w/ out-of-order msgs, too) 25

The header Wikipedia Lookup 26

Wikipedia interface (just like before) function searchWikipedia(term) { return $.ajaxAsObservable( { url: " dataType: "jsonp", data: { action: "opensearch", search: term, format: "json" } }).Select(function (d) { return d.data[1]; }); } 27

The input, throttled $(document).ready(function () { var terms = $("#searchInput").toObservable("keyup").Select(function (event) { return $(event.target).val(); }).Throttle(250); // Time to compose stuff here... }); 28

We want to achieve this composition 29

How to compose our two components? 1)Observable sequence of strings 2)Function from a string to an observable sequence that contains an array with the results var searchObservable = terms.Map(function (term) { return searchWikipedia(term); }); 30

Why is this solution incorrect? input type: Observable[string] type of searchWikipedia: string  Observable[Array[string]] hence Map’s result type: Observable[Observable[Array[string]] while we want Observable[Array[string]] hence we need to flatten the inner observable sequences 31

Correct colution SelectMany: projects each value of an observable sequence to an observable sequence and flattens the resulting observable sequences into one sequence. var searchObservable = terms.SelectMany(function (term) { return searchWikipedia(term); }); 32

Bind results to a UI As in Section 6. 33

Out of order sequences 34

Must suppress the older request 35

.Select().Switch() var searchObservable = terms.Select(searchWikipedia); // Observable[Observable[…]].Switch(); // Switch subscribes to latest sequence 36

Semantics of Switch 37

Summary From non-composable event handlers to composable observable sequences (streams) Read the full tutorial, which contains one more interesting section, at start reading on page 7 (Exercise 2) 38