Slide 1

Slide 1 text

Intro to Functional Reactive Programming Juan Gomez

Slide 2

Slide 2 text

• "Original FRP" refers to denotational and continuous-time functional programming using behaviors and events. • Rx is reactive programming combined with functional programming techniques. • Great post about the name controversy by André Staltz https://medium.com/@andrestaltz/why-i-cannot-say-frp- but-i-just-did-d5ffaa23973b Wait, you mean Reactive Programming?

Slide 3

Slide 3 text

Agenda • Brief introduction to Rx and why we want to use it. • Observables and useful operators to transform Observables. • Intermediate concepts around RxJava

Slide 4

Slide 4 text

What Is Functional Reactive Programming? • A style of programming based on two key ideas: continuous time-varying behaviors, and event-based reactivity. • Popularized by Erik Meijer when he created the Rx library for .NET while at Microsoft.

Slide 5

Slide 5 text

What are Reactive Extensions? • It’s a library that allows you to use FRP in many Programming Language • Allows you to represent asynchronous data streams with “Observables” • And to parameterize the concurrency in those asynchronous data streams using “Schedulers”.

Slide 6

Slide 6 text

What are Reactive Extensions? • Abstracts away concerns about things like: ✦ low-level threading ✦ synchronization ✦ thread-safety ✦ concurrent data structures.

Slide 7

Slide 7 text

Rx Family • C#: Rx.NET • JavaScript: RxJS • RxJava (Java, Scala, Groovy, Clojure, Kotlin) • Ruby: Rx.rb • Python: RxPY • More at: http://reactivex.io/

Slide 8

Slide 8 text

Why Functional Reactive Programming • Writing concurrent programs correctly is difficult. • You can transform & compose asynchronous operations. • High-level abstractions • Standard error handling

Slide 9

Slide 9 text

Multithreading is hard! This is a lesson I seem to learn every few years: multithreading is hard.
 Once you think you now understand it and are an expert, you are heading soon to another painful lesson that multithreading is hard. Dianne Hackborn April 2012

Slide 10

Slide 10 text

Push vs Pull

Slide 11

Slide 11 text

Observables event Iterable (pull) Observable (push) retrieve data T next() onNext(T) discover error throws Exception onError(Exception) complete !hasNext() onCompleted() Using the concept of “duality” we can derive the Observable type from an Iterable

Slide 12

Slide 12 text

onNext, onCompleted, onError An Observer implements a subset of the following methods: • onNext: We call this method whenever the Observable emits an item. • onError: Call this method to indicate that the Observable has failed and will not make further calls to onNext or onCompleted. • onCompleted: Call this method after you have called onNext for the final time and if we have not encountered any errors.

Slide 13

Slide 13 text

The “Subscribe” method

Slide 14

Slide 14 text

No Magic! • “Make the Magic go away” By Uncle Bob Martin: http://blog.8thlight.com/uncle-bob/2015/08/06/let- the-magic-die.html • Write a primitive Rx framework in JavaScript: http://reactivex.io/learnrx/

Slide 15

Slide 15 text

RxJava • It’s a JVM implementation of Reactive Extensions • Started at Netflix but now Open Sourced • Supports Java 6+ & Android 2.3+ • Java 8 lambda support

Slide 16

Slide 16 text

RxJava on Java 7 aObservable.filter(new Func1() { public Boolean call(Integer n) { return n % 2 == 0; } }) .map(new Func1() { public Integer call(Integer n) { return n * n; } }) .subscribe(new Action1() { public void call(Integer n) { System.out.println(n); } });

Slide 17

Slide 17 text

Retrolambda Retrolambda lets you take advantage of Java 8 features like lambda expressions, method references and try-with-resources statements on Java 7, 6 or 5. • Retrolambda • https://github.com/orfjackal/retrolambda • Gradle plugin • https://github.com/evant/gradle-retrolambda

Slide 18

Slide 18 text

RxJava using Retrolambda aObservable.filter(n -> n % 2 == 0) .map(n -> n * n) .subscribe(System.out::println);

Slide 19

Slide 19 text

Taken from https://gist.github.com/staltz/868e7e9bc2a7b8c1f754 by André Staltz

Slide 20

Slide 20 text

Operators in RxJava aObservable.map(x -> x*x) //Square .reduce((a, b) -> a+b) //Sum .subscribe(x -> println(x)); //Show

Slide 21

Slide 21 text

Marble diagrams Check out http://rxmarbles.com

Slide 22

Slide 22 text

Creating an Observable

Slide 23

Slide 23 text

Creating an Observable List aList = ...; ob = Observable.create(subscriber -> { try { for (String s : aList) { if (subscriber.isUnsubscribed()) return; subscriber.onNext(s); } subscriber.onCompleted(); } catch (Exception e) { subscriber.onError(e); } });

Slide 24

Slide 24 text

Creating an Observable List aList = ...; Observable ob = Observable.from(aList);

Slide 25

Slide 25 text

Creating an Observable Observable> ob = Observable.just(aList); Observable ob2 = Observable.just("Some String");

Slide 26

Slide 26 text

Creating an Observable • repeat( ) • range( ) • interval( ) • timer( ) • empty( ) • error( ) • More at: https://github.com/ReactiveX/RxJava/wiki/Creating- Observables

Slide 27

Slide 27 text

Transforming Observables

Slide 28

Slide 28 text

Transforming Observables Observable.range(0, 5) .map(x -> toBinaryString(x*x)) .subscribe(s -> println(s), err -> err.printStackTrace(), () -> println("done")); 0 1 100 1001 10000 done

Slide 29

Slide 29 text

Transforming Observables

Slide 30

Slide 30 text

Transforming Observables 1 2 2 3 3 3 Observable.range(1, 3) .flatMap(x -> Observable.just(x).repeat(x)) .subscribe(System.out::println);

Slide 31

Slide 31 text

Filtering Observables

Slide 32

Slide 32 text

Filtering Observables 0 2 4 6 8 Observable.range(0, 10) .filter(x -> (x % 2) == 0) .subscribe(System.out::println);

Slide 33

Slide 33 text

Filtering Observables • distinct( ) • first( ) • take( ) • skip( ) • elementAt( ) • sample( ) • more... • More at: https://github.com/ReactiveX/RxJava/wiki/Filtering-Observables

Slide 34

Slide 34 text

Aggregate Operators

Slide 35

Slide 35 text

Aggregate Operators 3628800 Observable.range(1, 10) .reduce((a, b) -> a*b) .subscribe(System.out::println);

Slide 36

Slide 36 text

Combining Observables

Slide 37

Slide 37 text

Combining Observables a_A b_B c_C Observable lower = Observable.from(new String[]{"a", "b", "c"}); Observable upper = Observable.from(new String[]{"A", "B", "C"}); Observable.zip(lower, upper, Pair::create) .map(pair -> pair.first +"_" +pair.second) .subscribe(System.out::println);

Slide 38

Slide 38 text

Schedulers • observeOn • specify on which Scheduler a Subscriber should observe the Observable • subscribeOn • specify which Scheduler an Observable should use when its subscription is invoked • https://github.com/ReactiveX/RxJava/wiki/ Scheduler

Slide 39

Slide 39 text

Backpressure • Backpressure is the situation in which an Observable is emitting items more rapidly than an operator or subscriber can consume them. • RxJava offers a variety of strategies like throttling with which you can exercise flow control in order to alleviate the problems caused by backpressure. • https://github.com/ReactiveX/RxJava/wiki/Backpressure

Slide 40

Slide 40 text

Hot and Cold Observables • A “cold” Observable waits to start emitting items until an observer subscribes, and so an observer can “observe” the whole sequence. • A “hot” Observable may begins emitting items as soon as it is created.

Slide 41

Slide 41 text

RxAndroid • Android specific bindings for RxJava. • https://github.com/ReactiveX/RxAndroid • Scheduler on main UI thread or a given Android Handler thread. • AndroidSchedulers • HandlerScheduler

Slide 42

Slide 42 text

RxAndroid

Slide 43

Slide 43 text

Summary • Embrace Reactive and Functional Thinking • Manipulating Streams of data simplifies how you think (and build) your apps. • RxJava is a powerful tool to improve your Android Code

Slide 44

Slide 44 text

Useful links • Grokking RxJava by Dan Lew: http://blog.danlew.net/2014/09/15/grokking-rxjava-part-1/ • Introduction to Reactive Programming by André Staltz https://gist.github.com/staltz/868e7e9bc2a7b8c1f754 • Guide to Rx Operators: http://reactivex.io/documentation/operators.html • RxJava docs: https://github.com/ReactiveX/RxJava/wiki/

Slide 45

Slide 45 text

We’re hiring! Senior Software Engineer - Android http://nflx.io/android-job Many more at: http://netflix.com/jobs

Slide 46

Slide 46 text

Thank You! Twitter: @_juandg Email: jgomez@netflix.com Lanyrd: lanyrd.com/profile/juandg/