reactive thinking in java

50
Reactive Thinking in Java Yakov Fain, Farata Systems @yfain

Upload: yakov-fain

Post on 15-Apr-2017

751 views

Category:

Software


0 download

TRANSCRIPT

Page 1: Reactive Thinking in Java

Reactive Thinking in Java

Yakov Fain, Farata Systems

@yfain

Page 2: Reactive Thinking in Java

Reactive thinking is not new

Page 3: Reactive Thinking in Java

Бди!

Козьма Прутков

Reactive thinking is not new

Page 4: Reactive Thinking in Java

Reactive thinking is not new

Page 5: Reactive Thinking in Java

The reactive style app

• Message-driven - components communicates via notifications

• Non-imperative - the app logic is coded in async, non-blocking, composable functions

• The data moves through your app’s algorithm

www.reactivemanifesto.org

Page 6: Reactive Thinking in Java

Java concurrency• Blocking I/O is the problem

• Future.get() - blocks till all threads are complete

• CompletableFuture.supplyAsync(task).thenAccept(action) - what if the tasks need to fetch millions of records?

Page 7: Reactive Thinking in Java

Some open-source Rx libraries

• RxJava

• RxAndroid, RxJavaFX, RxSwing

• Rx.NET, RxCpp, RxJS, Rx.rb, Rx.py, RxSwift, RxScala, RxPHP

http://reactivex.io

JDK 9 will include reactive streams in java.util.concurrent.Flow

Page 8: Reactive Thinking in Java

Main RxJava players• Observable - producer of data

• Observer - consumer of observable sequences

• Subscriber - connects observer with observable

• Operator - en-route data transformation

• Scheduler - multi-threading support

Page 9: Reactive Thinking in Java

beers.forEach(brr -> { if ("USA".equals(brr.country)){ americanBeers.add(brr); } });

Java Iterable: a pull

Page 10: Reactive Thinking in Java

beers.stream() .skip(1) .limit(3) .filter(b -> "USA".equals(b.country)) .map(b -> b.name + ": $" + b.price) .forEach(beer -> System.out.println(beer));

Java 8 Stream: a pull

Page 11: Reactive Thinking in Java

A fool with a tool is still a foolАмериканская народная мудрость

Page 12: Reactive Thinking in Java

A pull with a tool is still a pull

A fool with a tool is still a foolАмериканская народная мудрость

Yakov Fain

Page 13: Reactive Thinking in Java

Observable is an Iterable inside out

Page 14: Reactive Thinking in Java

Word Antonym

Iterable Observable

Iterator Observer

Pull Push

Page 15: Reactive Thinking in Java

Data Source

Data Flow

Page 16: Reactive Thinking in Java

Observable Data Source

Data Flow

Page 17: Reactive Thinking in Java

Observable Data Source

Data Flow

Page 18: Reactive Thinking in Java

Observable SubscriberObserver Data Source

Data Flow

Page 19: Reactive Thinking in Java

Observable

onNext()

SubscriberObserver

onError()onCompleted()

Data Source

Data Flow

Page 20: Reactive Thinking in Java

Event-driven push

Subscribe to messages from Observable and handle them by Observer

Observable

Observer

Subscriber

Observer

Subscriber

push

push

push

Observer

Subscriber

Page 21: Reactive Thinking in Java

Observable.subscribe(Subscriber)

class Subscriber implements Observer {}

Page 22: Reactive Thinking in Java

observableBeer .skip(1) .take(3) .filter(b -> "USA".equals(b.country)) .map(b -> b.name + ": $" + b.price) .subscribe( beer -> System.out.println(beer), err -> System.out.println(err), () -> System.out.println("Streaming is complete") );

Rx Observable: a push

Page 23: Reactive Thinking in Java

Demo HelloObservable

Get rxjava.jar on http://search.maven.org

Page 24: Reactive Thinking in Java

An Operator

Observable Observable

A transforming function

Page 25: Reactive Thinking in Java

An Operator

Observable Observable

A transforming function

observableBeer .filter(b -> "USA".equals(b.country))

Page 26: Reactive Thinking in Java

An Operator

Observable Observable

A transforming function

An operator is a higher-order function

observableBeer .filter(b -> "USA".equals(b.country))

pure function

Page 27: Reactive Thinking in Java

Marble Diagrams

http://rxmarbles.com

Page 28: Reactive Thinking in Java

Observable map(function){}

Page 29: Reactive Thinking in Java

Observable filter(function){}

Page 30: Reactive Thinking in Java

Operator chaining: map and filter

Page 31: Reactive Thinking in Java

RX: the data moves across your algorithm

Page 32: Reactive Thinking in Java

Observable

Operator

Observable

Operator

ObservableOperator

ObservableOperator

Page 33: Reactive Thinking in Java

Creating an Observable• Observable.create() - returns Observable that can invoke methods on Observer

• Observable.from() - converts an Iterable or Future into Observable

• Observable.fromCallable() - converts a Callable into Observable

• Observable.empty() - returns empty Observable that invokes onCompleted()

• Observable.range() - returns a sequence of integers in the specified range

• Observable.just() - converts up to 10 items into Observable

Page 34: Reactive Thinking in Java

Demo BeerClient

Page 35: Reactive Thinking in Java

Functions with side effects

• doOnNext()

• doOnError()

• doOnCompleted()

• doOnEach()

• doOnSubscribe()

Affect environment outside the function.

Page 36: Reactive Thinking in Java

Error HandlingObserver Observable

next

error

completed

Page 37: Reactive Thinking in Java

Error-handling operators• Errors sent using onError() kill the subscription

• retryWhen() - intercept, anylize the error, resubscribe

• onErrorResumeNext() - used for failover to another Observable

• onResumeReturn() - returns an app-specific value

Page 38: Reactive Thinking in Java

Demo BeerClientWithFailover

Page 39: Reactive Thinking in Java

The flatMap() operator

Page 40: Reactive Thinking in Java

.flatMap()Observable

Page 41: Reactive Thinking in Java

Demo composingObservables/ObservableDrinks

Page 42: Reactive Thinking in Java

Schedulers

Page 43: Reactive Thinking in Java

Concurrency with Schedulers

• An observable stream is single-threaded by default

• subscribeOn(strategy) - run Observable in a separate thread

• observeOn(strategy) - run Observer in a separate thread

Page 44: Reactive Thinking in Java

Multi-threading strategies• Schedulers.computation() - for computations: # of threads <= # of cores

• Schedulers.io() - for long running communications; backed by a thread pool

• Schedulers.newThread() - new thread fo each unit of work

• Schedulers.from(Executor) - a wrapper for Java Executor

• Scedulers.trampoline() - queues the work on the current thread

• AndroidSchedulers.mainThread() - handle data on the main thread (RxAndroid)

Page 45: Reactive Thinking in Java

Switching threads

Operator1() Operator2() ObserveOn()Observable

Subscriber

Thread 1

Thread 2

Page 46: Reactive Thinking in Java

Parallel processing

Operator1() Operator2() flatMap()Observable

Subscriber

Thread 1

Observable/Thr2

Observable/Thr3

Observable/ThrN

Page 47: Reactive Thinking in Java

Demo schedulers/SubscribeOnObserveOn

schedulers/ParallelStreams

Page 48: Reactive Thinking in Java

Hot and cold observables

• Cold: emits items only when someone subscribes to it

• Hot: emits items when it’s created regardless if there is a subscriber or not

Page 49: Reactive Thinking in Java

Backpressure• Throttling: sample(), throttleFirst(), debounce()

• Buffers: buffer()

• Window: window(n)

• Reactive pull: Subscriber.request(n)

https://github.com/ReactiveX/RxJava/wiki/Backpressure

Page 50: Reactive Thinking in Java

Links

• Code samples and slides: https://github.com/yfain/rxjava

• Our company: faratasystems.com

• Blog: yakovfain.com

• Twitter:@yfain discount code: faindz