Intro to RxJava on Android
Chris Arriola
Functional Reactive Programming
Makes dealing with concurrency easy
Makes code a lot more concise and readable
Encourages defensive programming and makes error handling easy
Increases the level of abstraction
Why consider RxJava?
Nested Network Call w/o RxJava
Nested Network Call w/ RxJava
What is RxJava?Java implementation of .NET’s Reactive Extensions
Specification for Functional Reactive Programming (FRP)
Programming with asynchronous data streams
Not a new concept. Think: click events/handlers, event bus, etc.
Reactive part
Can combine, create, filter, map, or transform any stream
Functional part
Core RxJava Constructs● Observable
● Observer
● Operator
Emits items in a sequence
Like an Iterator, it produces all items in a sequence
Each emitted item will be propagated to each Observer
Observable
ObserverObserver (aka the “subscriber”) subscribes to Observable
Observers are notified of a new item through #onNext(...)
Observers are notified when there sequence completes/fails through #onCompleted()/#onError()
Creating an Observable● Create an Observable using #create(...)
Creating an Observable● Create an Observable from item/s using #just(...)
● Create an Observable from an Iterable using #from(...)
● Create an Observable that emits items given an interval using #interval(...)
Creating an Observable (cont’d)
● Defer creation of Observable until subscription
Subscribing to an Observable● Observer has #onNext(...), #onCompleted(...), and #onError(...)
Unsubscribing to an Observable
● Observable#subscribe(...) returns a Subscription object from which the caller can invoke Subscription#unsubscribe()
Operator
● Most powerful part about Observables is that you can transform them and perform functional style programming—map(),
debounce(), filter(), etc.
● Transform Observable instances through Operators
Operator
Transforming an Observable● Transform values emitted by Observable using the #map(...)
operator
Filtering an Observable● Filter values emitted by Observable using #filter(...) operator
Scheduling an Observable● Specify a Scheduler where the Observable should operate using
#subscribeOn(...), specify a Scheduler where the Observable should notify its observers using #observeOn(...)
Error Handling● Re-subscribe/retry when the Observable emits an error
Ex. Double Clicks
Stream of clicks
Accumulate clicks in a list
Get length of list
Filter
Ex. Double ClicksSimulate a stream of clicks:
Ex. Double ClicksAccumulate clicks until 250 ms has passed between clicks:
Ex. Double ClicksMap the length of each list & filter for sizes >= 2:
GitHub Example● Interact with GitHub’s API using Retrofit and RxJava
○ https://github.com/arriolac/GithubRxJava
Questions??
Thank You!
Twitter: @arriolachris