Slide 1

Slide 1 text

MADRID · NOV 27-28 · 2015 RxJava in practice Javier Gamarra

Slide 2

Slide 2 text

MADRID · NOV 27-28 · 2015 http://kcy.me/29crj (slides) & http://kcy.me/296bu (commits)

Slide 3

Slide 3 text

MADRID · NOV 27-28 · 2015 Environment Eclipse | Android Studio (RxAndroid) RxJava.jar [Java 8] || [Retrolambda] :P

Slide 4

Slide 4 text

MADRID · NOV 27-28 · 2015 Environment Android Studio: compile 'io.reactivex:rxandroid:1.0.1' compile 'io.reactivex:rxjava:1.0.16' Eclipse: ● Copy jars to lib/ and add jar in project

Slide 5

Slide 5 text

MADRID · NOV 27-28 · 2015 Github ● http://kcy.me/296bu ● koans ● código ● commit a commit ● Podéis preguntarme en cualquier momento

Slide 6

Slide 6 text

MADRID · NOV 27-28 · 2015 Who? Javier Gamarra / @nhpatt @liferay @cyliconvalley / @agilespain

Slide 7

Slide 7 text

MADRID · NOV 27-28 · 2015 Ask! Please? Pretty please? Please pretty please with sugar on top?

Slide 8

Slide 8 text

MADRID · NOV 27-28 · 2015 Background?

Slide 9

Slide 9 text

MADRID · NOV 27-28 · 2015 Why?

Slide 10

Slide 10 text

MADRID · NOV 27-28 · 2015 Why? (in java) multithreading is hard futures are complicated callbacks are hell

Slide 11

Slide 11 text

MADRID · NOV 27-28 · 2015 Rx comes to the rescue!

Slide 12

Slide 12 text

MADRID · NOV 27-28 · 2015 a library to represent any operation as an asynchronous data stream on any thread, declaratively composed, and consumed by multiple objects

Slide 13

Slide 13 text

MADRID · NOV 27-28 · 2015 a library

Slide 14

Slide 14 text

MADRID · NOV 27-28 · 2015 A library? Extensions to .NET framework Netflix

Slide 15

Slide 15 text

MADRID · NOV 27-28 · 2015 Libraries are tools If all you have is a hammer, everything looks like a nail

Slide 16

Slide 16 text

MADRID · NOV 27-28 · 2015 a library to model Observables & Subscribers

Slide 17

Slide 17 text

MADRID · NOV 27-28 · 2015 Observables and Subscribers An Observable emits items. A Subscriber consumes those items.

Slide 18

Slide 18 text

MADRID · NOV 27-28 · 2015 Observer pattern?

Slide 19

Slide 19 text

MADRID · NOV 27-28 · 2015 My very first observable Observable myObs = Observable. create(new Observable. OnSubscribe() { @Override public void call(Subscriber subscriber) { subscriber.onNext( "Hi!"); subscriber.onCompleted(); } });

Slide 20

Slide 20 text

MADRID · NOV 27-28 · 2015 My very first subscriber Subscriber mySubs = new Subscriber() { @Override public void onCompleted() { } @Override public void onError(Throwable throwable) { } @Override public void onNext(String s) { System. out.println(s); } };

Slide 21

Slide 21 text

MADRID · NOV 27-28 · 2015 My very first subscription myObs.subscribe(mySubs);

Slide 22

Slide 22 text

MADRID · NOV 27-28 · 2015 A bit verbose... Let’s simplify with Java8 and RxJava ● lamdbas ● Observable.just ● .subscribe()

Slide 23

Slide 23 text

MADRID · NOV 27-28 · 2015 That’s better... Observable .just("Hi!") .subscribe(System.out::println);

Slide 24

Slide 24 text

MADRID · NOV 27-28 · 2015 Why? More than the observer pattern ● Observables only emit when someone listening ● OnFinished ● OnError

Slide 25

Slide 25 text

MADRID · NOV 27-28 · 2015 Let’s use those differences subscribe admits 3 parameters ● OnNext ● OnFinished ● OnError

Slide 26

Slide 26 text

MADRID · NOV 27-28 · 2015 You said “items” Observable.from admits a list of elements

Slide 27

Slide 27 text

MADRID · NOV 27-28 · 2015 Ok, let’s recap… Iterators?

Slide 28

Slide 28 text

MADRID · NOV 27-28 · 2015 Iterators? ● Iterators are pull and synchronous ● Subscribers are push and asynchronous

Slide 29

Slide 29 text

MADRID · NOV 27-28 · 2015 to represent any operation as an “asynchronous data stream”

Slide 30

Slide 30 text

MADRID · NOV 27-28 · 2015 Everything is a stream

Slide 31

Slide 31 text

MADRID · NOV 27-28 · 2015 Everything is a stream We can model everything as a stream

Slide 32

Slide 32 text

MADRID · NOV 27-28 · 2015 Everything is a stream A network call is also a stream Like using retrofit with this API

Slide 33

Slide 33 text

MADRID · NOV 27-28 · 2015 “declaratively composed”

Slide 34

Slide 34 text

MADRID · NOV 27-28 · 2015 Operators

Slide 35

Slide 35 text

MADRID · NOV 27-28 · 2015 Operators Transform a stream rxmarbles and android app

Slide 36

Slide 36 text

MADRID · NOV 27-28 · 2015 Operators Map

Slide 37

Slide 37 text

MADRID · NOV 27-28 · 2015 Map List severalThings = Arrays.asList("1", "2"); Observable.from(severalThings) .map((s) -> “Element “ + s) .subscribe(System.out::println);

Slide 38

Slide 38 text

MADRID · NOV 27-28 · 2015 Map We can return another type: List severalThings = Arrays.asList("1", "2"); Observable.from(severalThings) .map(Integer::valueOf) .subscribe(System.out::println);

Slide 39

Slide 39 text

MADRID · NOV 27-28 · 2015 Map Let’s do the same with our repos… And… I can’t because we return a List And using Observable.from… NOP

Slide 40

Slide 40 text

MADRID · NOV 27-28 · 2015 Flatmap Flatmap Obs -> elements

Slide 41

Slide 41 text

MADRID · NOV 27-28 · 2015 Flatmap service.listRepos("nhpatt") .flatMap(Observable::from) .map(Repo::getName) .map((s) -> s.replace("-", " ")) .subscribe(System.out::println);

Slide 42

Slide 42 text

MADRID · NOV 27-28 · 2015 Flatmap Concatmap -> ordered flatmap

Slide 43

Slide 43 text

MADRID · NOV 27-28 · 2015 Filter service.listRepos("nhpatt") .flatMap(Observable::from) .map(Repo::getName) .map((s) -> s.replace("-", " ")) .filter((s) -> s.startsWith("Android")) .subscribe(System.out::println);

Slide 44

Slide 44 text

MADRID · NOV 27-28 · 2015 Scan & old code service.listRepos("nhpatt") .flatMap(Observable::from) .map(Repo::getName) .map((s) -> s.replace("-", " ")) .filter((s) -> s.startsWith("Android")) .take(2) .map(String::length) .scan((x, y) -> x * y) .subscribe(System.out::println);

Slide 45

Slide 45 text

MADRID · NOV 27-28 · 2015 Scan & old code (l) -> { int result = 0; int i = 0; int oldLength = 1; for (Repo repo : l) { String name = repo.getName(); String replacedName = name.replace( "-", " "); if (replacedName.startsWith( "Android") && i < 2) { result = replacedName.length() * oldLength; oldLength = result; System.out.println(result); i++; } } return result;

Slide 46

Slide 46 text

MADRID · NOV 27-28 · 2015 Operators ● merge ● flatMap ● zip Nice things™ : parallel jobs!

Slide 47

Slide 47 text

MADRID · NOV 27-28 · 2015 Zipping requests Observable repo = service.listRepos("nhpatt") .flatMap(Observable::from) .take(1); Observable commit = service.listCommits("nhpatt", "Android") .flatMap(Observable::from) .take(1); Observable.zip(repo, commit, this::updateCommit).subscribe (repo1 -> { System.out.println(repo1.getCommit().getUrl()); });

Slide 48

Slide 48 text

MADRID · NOV 27-28 · 2015 Operators Amazing documentation ● Async ● Blocking ● Combining ● Conditional ● Error handling ● Filtering ● Mathematical ● Creation ● String ● Transforming ● Utility

Slide 49

Slide 49 text

MADRID · NOV 27-28 · 2015 Subscribers are asynchronous? No, not really

Slide 50

Slide 50 text

MADRID · NOV 27-28 · 2015 “on any thread”

Slide 51

Slide 51 text

MADRID · NOV 27-28 · 2015 Schedulers!

Slide 52

Slide 52 text

MADRID · NOV 27-28 · 2015 Schedulers I define an API declaratively and later in the implementation run it: asynchronously or in a separate Thread or in a Threadpool or synchronously ...

Slide 53

Slide 53 text

MADRID · NOV 27-28 · 2015 Schedulers .subscribeOn(Schedulers...) .observeOn(Schedulers...) ● io ● computation ● newThread ● trampoline ● test

Slide 54

Slide 54 text

MADRID · NOV 27-28 · 2015 Schedulers service.listRepos("nhpatt") .subscribeOn(Schedulers.immediate()) .observeOn(Schedulers.immediate()) .subscribe(System.out::println);

Slide 55

Slide 55 text

MADRID · NOV 27-28 · 2015 Schedulers RxJava operators have default threads Interval?

Slide 56

Slide 56 text

MADRID · NOV 27-28 · 2015 Use cases?

Slide 57

Slide 57 text

MADRID · NOV 27-28 · 2015 Use cases ● Autocomplete with debounce | sample… ● Accumulate calls with buffer... ● Polling with timeout | window… ● Form Validation with combineLatest… ● Retrieve data fast from cache | network call with concat | merge… ● Button click with delay, listen on other thread

Slide 58

Slide 58 text

MADRID · NOV 27-28 · 2015 Android?

Slide 59

Slide 59 text

MADRID · NOV 27-28 · 2015 Why?

Slide 60

Slide 60 text

MADRID · NOV 27-28 · 2015 Why? (in android) Main/UI thread and background problem ● Can’t do heavy tasks on UI ● Can’t update view on background ● AsyncTasks are bad ● Handlers can leak

Slide 61

Slide 61 text

MADRID · NOV 27-28 · 2015 How RxAndroid helps?

Slide 62

Slide 62 text

MADRID · NOV 27-28 · 2015 Android schedulers service.listRepos("nhpatt") .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(newRepos -> { repos.addAll(newRepos); adapter.notifyDataSetChanged(); });

Slide 63

Slide 63 text

MADRID · NOV 27-28 · 2015 Orientation Problem Orientation Problem ● onCreate gets called again ● state is lost

Slide 64

Slide 64 text

MADRID · NOV 27-28 · 2015 Orientation Problem Programmer’s job: ● Store/Restore state ● Restore view ● Call again the user task? ● Wait until it finishes?

Slide 65

Slide 65 text

MADRID · NOV 27-28 · 2015 How RxAndroid helps?

Slide 66

Slide 66 text

MADRID · NOV 27-28 · 2015 Orientation Problem Observable is easy to persist (retain | singleton) Observable can continue (cache and retry) RxLifecycle

Slide 67

Slide 67 text

MADRID · NOV 27-28 · 2015 Orientation Problem Observable> github = RetrofitService. getGithub() .listRepos("nhpatt") .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .cache();

Slide 68

Slide 68 text

MADRID · NOV 27-28 · 2015 More Android Lifecycle (RxLifecyle) Views (RxBinding)

Slide 69

Slide 69 text

MADRID · NOV 27-28 · 2015 But...

Slide 70

Slide 70 text

MADRID · NOV 27-28 · 2015 But... Subscriptions leak memory :’( We have to call to unsubscribe (CompositeSubscription helps) And don’t include references to the object/activity

Slide 71

Slide 71 text

MADRID · NOV 27-28 · 2015 Easy to unsubscribe @Override protected void onStop() { super.onStop(); subscription.unsubscribe(); } .isUnsubscribed() :(

Slide 72

Slide 72 text

MADRID · NOV 27-28 · 2015 Let’s recap

Slide 73

Slide 73 text

MADRID · NOV 27-28 · 2015 a library to represent any operation as an asynchronous data stream on any thread, declaratively composed, and consumed by multiple objects

Slide 74

Slide 74 text

MADRID · NOV 27-28 · 2015 a library to represent any operation as an observable on any thread, declaratively composed, and consumed by multiple objects

Slide 75

Slide 75 text

MADRID · NOV 27-28 · 2015 a library to represent any operation as an observable with schedulers declaratively composed, and consumed by multiple objects

Slide 76

Slide 76 text

MADRID · NOV 27-28 · 2015 a library to represent any operation as an observable with schedulers and operators and consumed by multiple objects

Slide 77

Slide 77 text

MADRID · NOV 27-28 · 2015 a library to represent any operation as an observable with schedulers and operators listened by subscribers

Slide 78

Slide 78 text

MADRID · NOV 27-28 · 2015 But...

Slide 79

Slide 79 text

MADRID · NOV 27-28 · 2015 But... ● Learning curve ● Hard to debug (Frodo library) ● Backpressure

Slide 80

Slide 80 text

MADRID · NOV 27-28 · 2015 Questions?

Slide 81

Slide 81 text

MADRID · NOV 27-28 · 2015 Where to know more... ● reactivex.io (amazing docs) ● RxJava wiki ● Dan Lew ● Use cases

Slide 82

Slide 82 text

MADRID · NOV 27-28 · 2015 Where to know more... nhpatt (twitter | github | email | slack) I’ll do anything for good votes

Slide 83

Slide 83 text

MADRID · NOV 27-28 · 2015 Feedback Click here :P

Slide 84

Slide 84 text

MADRID · NOV 27-28 · 2015 RxJava in practice Javier Gamarra

Slide 85

Slide 85 text

MADRID · NOV 27-28 · 2015 Other interesting operators...

Slide 86

Slide 86 text

MADRID · NOV 27-28 · 2015 Take service.listRepos("nhpatt") .flatMap(Observable::from) .map(Repo::getName) .map((s) -> s.replace("-", " ")) .filter((s) -> s.startsWith("Android")) .take(2) .subscribe(System.out::println);

Slide 87

Slide 87 text

MADRID · NOV 27-28 · 2015 Operators distinctUntilChanged compose

Slide 88

Slide 88 text

MADRID · NOV 27-28 · 2015 Errors?

Slide 89

Slide 89 text

MADRID · NOV 27-28 · 2015 onError() is called if an Exception is thrown at any time (this is cool) The operators don't have to handle the Exception No more callbacks Errors

Slide 90

Slide 90 text

MADRID · NOV 27-28 · 2015 Errors And we can customize the flow: onErrorResumeNext onErrorReturn retry ...

Slide 91

Slide 91 text

MADRID · NOV 27-28 · 2015 Why this is useful?

Slide 92

Slide 92 text

MADRID · NOV 27-28 · 2015 Why this is useful? Observables and subscribers can do anything

Slide 93

Slide 93 text

MADRID · NOV 27-28 · 2015 Why this is useful? Observable a database query Subscriber displaying results on the screen

Slide 94

Slide 94 text

MADRID · NOV 27-28 · 2015 Why this is useful? Observable a click on the screen Subscriber reacting to it

Slide 95

Slide 95 text

MADRID · NOV 27-28 · 2015 Why this is useful? Observable a stream of bytes from the internet Subscriber write them to disk

Slide 96

Slide 96 text

MADRID · NOV 27-28 · 2015 Why this is useful? Observable and Subscriber are independent of the transformations

Slide 97

Slide 97 text

MADRID · NOV 27-28 · 2015 Why this is useful? I can compose/chain any map/filter calls I want Only matters the return type

Slide 98

Slide 98 text

MADRID · NOV 27-28 · 2015 Side effects?

Slide 99

Slide 99 text

MADRID · NOV 27-28 · 2015 Side effects doOn methods: ● doOnNext() for debugging ● doOnError() for error handling ● doOnNext() to save/cache results

Slide 100

Slide 100 text

MADRID · NOV 27-28 · 2015 Side effects Observable someObservable = Observable .from(Arrays.asList(new Integer[]{2, 7, 11})) .doOnNext(System.out::println) .filter(prime -> prime % 2 == 0) .doOnNext(System.out::println) .count() .doOnNext(System.out::println) .map( number -> String.format(“Contains %d elements”, number) );

Slide 101

Slide 101 text

MADRID · NOV 27-28 · 2015 Side effects flatMap(id -> service.get() .doOnError(t -> { // report problem to UI }) .onErrorResumeNext(Observable.empty()))

Slide 102

Slide 102 text

MADRID · NOV 27-28 · 2015 Cold & Hot

Slide 103

Slide 103 text

MADRID · NOV 27-28 · 2015 Cold & Hot Observables only emit when someone listening? Cold observables only emit when subscribed But hot observables emit instantly

Slide 104

Slide 104 text

MADRID · NOV 27-28 · 2015 Cold & Hot You can convert between both states ● “Hot -> cold” using defer() or merge(), zip()... ● “Cold -> Hot” using publish() & connect()

Slide 105

Slide 105 text

MADRID · NOV 27-28 · 2015 Cold & Hot publish & connect? “like transactions” Assume everything is cold

Slide 106

Slide 106 text

MADRID · NOV 27-28 · 2015 Testing?

Slide 107

Slide 107 text

MADRID · NOV 27-28 · 2015 More cool things? ● testscheduler ● toIterator() ● Obs.error(), Obs.empty()

Slide 108

Slide 108 text

MADRID · NOV 27-28 · 2015 Subjects

Slide 109

Slide 109 text

MADRID · NOV 27-28 · 2015 Subjects Both observable & observer

Slide 110

Slide 110 text

MADRID · NOV 27-28 · 2015 Subjects AsyncSubject -> takeLast(1) PublishSubject -> publish() ReplaySubject -> replay()/cache() BehaviorSubject -> replay(1)/cache(1)

Slide 111

Slide 111 text

MADRID · NOV 27-28 · 2015 RxJava in practice Javier Gamarra