17
REACTIVE JAVA

Introduction to Reactive Java

Embed Size (px)

DESCRIPTION

Introduction to Reactive Java library created by Netflix

Citation preview

Page 1: Introduction to Reactive Java

REACTIVE JAVA

Page 2: Introduction to Reactive Java

REACTIVE

“readily responsive to a stimulus”

Merriam-Webster dictionary

Page 3: Introduction to Reactive Java

RX JAVA BY NETFLIX

• A library for composing asynchronous and event-based programs using observable sequences for the Java VM

• Implementation of Rx Observables from Microsoft

• Targets the JVM not a language. Currently supports Java, Groovy, Clojure, and Scala

• https://github.com/Netflix/RxJava

• Apache License, Version 2.0

Page 4: Introduction to Reactive Java

OBSERVABLE ->

OBSERVER ->

Page 5: Introduction to Reactive Java

SUBCRIPTIONS AND EVENTS

t

subscribe

onNext*

onCompleted | onError

Page 6: Introduction to Reactive Java

SERVICE RETURNING OBSERVABLE

public interface ShrödingersCat {

Observable<Boolean> alive();

}

cat

.alive()

.subscribe(status -> System.out.println(status));

Page 7: Introduction to Reactive Java

SERVICE RETURNING OBSERVABLE

public interface ShrödingersCat {

Observable<Boolean> alive();

}

cat

.alive()

.throttleWithTimeout(250, TimeUnit.MILLISECONDS)

.distinctUntilChanged()

.filter(isAlive -> isAlive)

.map(Boolean::toString)

.subscribe(status -> display.display(status));

Page 8: Introduction to Reactive Java

OBSERVER

public interface Observer<T> {

void onCompleted();

void onError(Throwable e);

void onNext(T args);

}

Page 9: Introduction to Reactive Java

SUBSCRIPTION

public interface Subscription {

void unsubscribe();

}

Page 10: Introduction to Reactive Java

CREATING OBSERVABLES

Observable<Boolean> watchTheCat =

Observable.create(observer -> {

observer.onNext(cat.isAlive());

observer.onCompleted();

return Subscriptions.empty();

});

• Executes all code when subscribed

• Not asynchronous, not really a stream

Page 11: Introduction to Reactive Java

CREATING OBSERVABLES

Observable.create(observer -> {

Future<?> future = executorService.submit(() -> {

observer.onNext(cat.isAlive());

observer.onCompleted();

});

return Subscriptions.from(future);

});

• Executes code in separate thread (from thread pool executorService)

• Stream of events is delivered by the executor thread

• Thread calling onNext() runs all the operations defined on observable

• Future is cancelled if client unsubscribes

Page 12: Introduction to Reactive Java

MARBLE DIAGRAM

Page 13: Introduction to Reactive Java

MERGE(OBSERVABLE...)

Page 14: Introduction to Reactive Java

CONCAT(OBSERVABLE...)

Page 15: Introduction to Reactive Java

DEBOUNCE(LONG TIEMOUT, TIMEUNIT TU)

Page 16: Introduction to Reactive Java

ZIP(OBSERVABLE, OBSERVABLE, FUNC2)

Page 17: Introduction to Reactive Java

HOW WE USE IT – DATA FILE DISCOVERYAmazon S3 Disk Memory

cache cache cache

mergeDelayError