SlideShare a Scribd company logo
RxJava:
Functional Reactive
Programming on Android
Alexey Chernin, Software Developer
Based on:
“What does it mean to be Reactive” - Erik Meijer
“Rx-Fy all the things!” - Benjamin Augustin
“RxJava Easy Wins” - Ron Shapiro
“Android reactive programming with Rxjava”
- Ivan Morgillo
“Rx in 15 Minutes” - Erik Meijer
“Functional Reactive Programming in the Netflix API”
- Ben Christensen
Based on:
"RxJava Essentials" by
Ivan Morgillo, May 2015
“Реактивный двигатель для вашего Android приложения”
- Матвей Мальков
https://github.com/ReactiveX/RxJava/wiki
“Learning RxJava (for Android) by example” - Kaushik Gopal
“Reactive Programming in Java 8 With RxJava”
- Russell Elledge
“Rx Workshop”
Reactive Systems are:
 Responsive: The system responds in a timely manner if at all possible.
 Resilient: The system stays responsive in the face of failure.
 Elastic: The system stays responsive under varying workload.
 Message Driven: Reactive Systems rely on asynchronous message-passing to
establish a boundary between components that ensures loose coupling, isolation,
location transparency, and provides the means to delegate errors as messages.
Published on September 16 2014. (v2.0)
The Reactive Manifesto
www.reactivemanifesto.org
Functional reactive programming is an idea from the late 90s
that inspired Erik Meijer, a computer scientist at Microsoft, to
design and develop the Microsoft Rx library.
From .NET to RxJava
In 2012, at Netflix, they started to port .NET Rx to the JVM.
With a post on the Netflix tech blog in February 2013, Ben
Christensen and Jafar Husain showed RxJava to the world
for the first time.
“Reactive programming is a programming paradigm based on the concept
of an asynchronous data flow. A data flow is like a river: it can be observed,
filtered, manipulated, or merged with a second flow to create a new flow for
a new consumer”. Ivan Morgillo
Pure functions always returns the same result for a given set of parameter values.
 No side effects caused by Class or Instance state.
 No side effects caused by I/O devices.
 No time related side effects.
Pure functions
Pure functions: example 1
• Store function as a variable
• Pass a function as a parameter
• Function can return a function
 Composition
 Lazy execution
Pure functions: example 2
Butter Knife by Jake Wharton
Retrofit by Square
Why Retrofit?
https://instructure.github.io/blog/2013/12/09/volley-vs-retrofit
Supports:
• Gson - JSON serialization.
• Simple - XML serialization.
• OkHttp - HTTP client.
• Robospice - asynchronous network requests.
Fast:
“Retrofit” - Jacob Tabak
“A Few Ok Libraries”
- Jake Wharton
The old way
o Extend AsyncTask to make HTTP request in background
o Build the query string from array of NameValuePairs (12 lines)
o Read InputStream into String (20 lines)
o Parse JSON (75 lines)
The rxjava-android module contains Android-specific bindings for RxJava. It
adds a number of classes to RxJava to assist in writing reactive components in
Android applications.
o It provides a Scheduler that schedules an Observable on a given Android
Handler thread, particularly the main UI thread.
o It provides operators that make it easier to deal with Fragment and Activity
life-cycle callbacks.
o It provides wrappers for various Android messaging and notification
components so that they can be lifted into an Rx call chain.
o It provides reusable, self-contained, reactive components for common
Android use cases and UI concerns. (coming soon).
The RxJava Android Module
Gradle and Maven Retrolambda Plugin
Project dependencies
o Observables and Iterables share a
similar API.
o Observable is the push equivalent of
Iterable, which is pull.
Iterable and Observable
With Iterable, the consumer synchronously pulls values from the producer
and the thread is blocked until these values arrive. By contrast, with
Observable, the producer asynchronously pushes values to the Observer
whenever values are available.
The Observer pattern is the perfect fit for any of these scenarios:
o When your architecture has two entities, one depending on the other, and you want to
keep them separated to change them or reuse them independently.
o When a changing object has to notify an unknown amount of related objects about its
own
o change.
o When a changing object has to notify other objects without making assumptions about
who these objects are.
Observer pattern
Observer and Subscription
Types of Observables
Subject
A subject is a object that can be an Observable and an Observer at the
same time. A subject can subscribe to an Observable, acting like an
Observer, and it can emit new items or even pass through the item it
received, acting like an Observable.
RxJava provides four different types of subjects:
o PublishSubject - emits all subsequently observed items to the
subscriber, once an Observer has subscribed.
o BehaviorSubject - emits the most recent item it has observed and all
subsequent observed items to each subscribed Observer.
o ReplaySubject - buffers all items it observes and replays them to any
Observer that subscribes.
o AsyncSubject - publishes only the last item observed to each
Observer that has subscribed, when the source Observable completes.
Schedulers
Observable creation
Observable creation: examples
o Observable.just("one", "two", "three");
o Observable.just("one", "two", "three").repeat(3);
o Observable.range(10, 3); - Takes two numbers as parameters: the first
one is the starting point, and the second one is the amount of numbers we
want to emit.
o Observable.interval(3, TimeUnit.SECONDS); - Takes two parameters: a
number that specifies the amount of time between two emissions, and the
unit of time to be used.
o Observable.timer(3, 3, TimeUnit.SECONDS); - Starts with an initial delay
(3 seconds in the example) and then keeps on emitting a new number
every N seconds (3 in the example).
Marble diagram
Transformations: one to one
Transformations: one to many
Transformations: scanning
Transformations: group by
Transformations: buffer
Filtering Observables
Observable.just("one", "two", "three").filter((s)->{
return !s.equals("two");
});
Filtering Observables
sample() creates a new Observable sequence that will emit the most recent item
emitted by the Observable source in a decided time interval.
Filtering Observables
debounce() starts its internal timer,
and if no new item is emitted during
this timespan, the last item is
emitted by the new Observable.
Combining Observables
Death to AsyncTasks
Example
Example
Example
Well documented
Questions?
Thank you for your attention

More Related Content

Viewers also liked (20)

Centurylink Enterprise Cloud & Network
Centurylink Enterprise Cloud & Network
Jake Weaver
 
програма геометрія 7 кл. 2015
програма геометрія 7 кл. 2015
Иван Лаврусенко
 
Brian stoke
Brian stoke
Bhagwan Das
 
Europese regelgeving ventilatieproducten | verordening 1253/2014 |AL-KO Lucht...
Europese regelgeving ventilatieproducten | verordening 1253/2014 |AL-KO Lucht...
duurzame verhalen
 
Tieto Retail Experience - How will the retail remain relevant for all of us?
Tieto Retail Experience - How will the retail remain relevant for all of us?
Tieto Corporation
 
"The (in)visible UX" - Claudio Beatrice
"The (in)visible UX" - Claudio Beatrice
nois3
 
Getting hands dirty with php7
Getting hands dirty with php7
Michelangelo van Dam
 
Journey’s end
Journey’s end
juanazufriategui
 
Corrientes geograficas 2016
Corrientes geograficas 2016
Sol Maria Pardo Santayana
 
Globalisation
Globalisation
khooky
 
Literary devices s1
Literary devices s1
Pato_Ch
 
"Codesign Tools and Techniques” - Alessio Ricco
"Codesign Tools and Techniques” - Alessio Ricco
nois3
 
Intro to Lean UX: How to do it quick & dirty - Workshop [6h]
Intro to Lean UX: How to do it quick & dirty - Workshop [6h]
Melissa Ng
 
Η ΔΥΝΑΜΗ ΤΗΣ ΣΚΕΨΗΣ
Η ΔΥΝΑΜΗ ΤΗΣ ΣΚΕΨΗΣ
Vassilis (BIll) Panopoulos M.B.A., M.H.R.M., M.M.M.
 
Intelligent IoT Gateway on OpenWrt
Intelligent IoT Gateway on OpenWrt
Tieto Corporation
 
Derechos de los niños
Derechos de los niños
jperezmuniz
 
History S4 Esquema de contenidos nodales Dic 2016
History S4 Esquema de contenidos nodales Dic 2016
lennyambrosini
 
History S5 Esquema de contenidos nodales Dic 2016
History S5 Esquema de contenidos nodales Dic 2016
lennyambrosini
 
Brand Management: Nike
Brand Management: Nike
Jessica McCarthy
 
Centurylink Enterprise Cloud & Network
Centurylink Enterprise Cloud & Network
Jake Weaver
 
Europese regelgeving ventilatieproducten | verordening 1253/2014 |AL-KO Lucht...
Europese regelgeving ventilatieproducten | verordening 1253/2014 |AL-KO Lucht...
duurzame verhalen
 
Tieto Retail Experience - How will the retail remain relevant for all of us?
Tieto Retail Experience - How will the retail remain relevant for all of us?
Tieto Corporation
 
"The (in)visible UX" - Claudio Beatrice
"The (in)visible UX" - Claudio Beatrice
nois3
 
Globalisation
Globalisation
khooky
 
Literary devices s1
Literary devices s1
Pato_Ch
 
"Codesign Tools and Techniques” - Alessio Ricco
"Codesign Tools and Techniques” - Alessio Ricco
nois3
 
Intro to Lean UX: How to do it quick & dirty - Workshop [6h]
Intro to Lean UX: How to do it quick & dirty - Workshop [6h]
Melissa Ng
 
Intelligent IoT Gateway on OpenWrt
Intelligent IoT Gateway on OpenWrt
Tieto Corporation
 
Derechos de los niños
Derechos de los niños
jperezmuniz
 
History S4 Esquema de contenidos nodales Dic 2016
History S4 Esquema de contenidos nodales Dic 2016
lennyambrosini
 
History S5 Esquema de contenidos nodales Dic 2016
History S5 Esquema de contenidos nodales Dic 2016
lennyambrosini
 

Similar to Sperasoft Talks: RxJava Functional Reactive Programming on Android (20)

RxJava@DAUG
RxJava@DAUG
Maxim Volgin
 
Streams, Streams Everywhere! An Introduction to Rx
Streams, Streams Everywhere! An Introduction to Rx
Andrzej Sitek
 
Introduction to RxJava on Android
Introduction to RxJava on Android
Chris Arriola
 
RxJava@Android
RxJava@Android
Maxim Volgin
 
Reactive Programming on Android - RxAndroid - RxJava
Reactive Programming on Android - RxAndroid - RxJava
Ali Muzaffar
 
RxJava pour Android : présentation lors du GDG Android Montréal
RxJava pour Android : présentation lors du GDG Android Montréal
Sidereo
 
Intro to Functional Programming with RxJava
Intro to Functional Programming with RxJava
Mike Nakhimovich
 
RxJava - introduction & design
RxJava - introduction & design
allegro.tech
 
Streamlining with rx
Streamlining with rx
Akhil Dad
 
Reactive Programming in Java 8 with Rx-Java
Reactive Programming in Java 8 with Rx-Java
Kasun Indrasiri
 
Reactive Functional Programming with Java 8 on Android N
Reactive Functional Programming with Java 8 on Android N
Shipeng Xu
 
Reactive Programming in Java by Mario Fusco - Codemotion Rome 2015
Reactive Programming in Java by Mario Fusco - Codemotion Rome 2015
Codemotion
 
Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...
Mario Fusco
 
Functional reactive programming
Functional reactive programming
Araf Karsh Hamid
 
Reactive programming on Android
Reactive programming on Android
Tomáš Kypta
 
Intro to Reactive Thinking and RxJava 2
Intro to Reactive Thinking and RxJava 2
JollyRogers5
 
Taming Asynchrony using RxJS
Taming Asynchrony using RxJS
Angelo Simone Scotto
 
Microservices Part 4: Functional Reactive Programming
Microservices Part 4: Functional Reactive Programming
Araf Karsh Hamid
 
Reactive programming with rx java
Reactive programming with rx java
CongTrung Vnit
 
RxJS - The Reactive extensions for JavaScript
RxJS - The Reactive extensions for JavaScript
Viliam Elischer
 
Streams, Streams Everywhere! An Introduction to Rx
Streams, Streams Everywhere! An Introduction to Rx
Andrzej Sitek
 
Introduction to RxJava on Android
Introduction to RxJava on Android
Chris Arriola
 
Reactive Programming on Android - RxAndroid - RxJava
Reactive Programming on Android - RxAndroid - RxJava
Ali Muzaffar
 
RxJava pour Android : présentation lors du GDG Android Montréal
RxJava pour Android : présentation lors du GDG Android Montréal
Sidereo
 
Intro to Functional Programming with RxJava
Intro to Functional Programming with RxJava
Mike Nakhimovich
 
RxJava - introduction & design
RxJava - introduction & design
allegro.tech
 
Streamlining with rx
Streamlining with rx
Akhil Dad
 
Reactive Programming in Java 8 with Rx-Java
Reactive Programming in Java 8 with Rx-Java
Kasun Indrasiri
 
Reactive Functional Programming with Java 8 on Android N
Reactive Functional Programming with Java 8 on Android N
Shipeng Xu
 
Reactive Programming in Java by Mario Fusco - Codemotion Rome 2015
Reactive Programming in Java by Mario Fusco - Codemotion Rome 2015
Codemotion
 
Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...
Mario Fusco
 
Functional reactive programming
Functional reactive programming
Araf Karsh Hamid
 
Reactive programming on Android
Reactive programming on Android
Tomáš Kypta
 
Intro to Reactive Thinking and RxJava 2
Intro to Reactive Thinking and RxJava 2
JollyRogers5
 
Microservices Part 4: Functional Reactive Programming
Microservices Part 4: Functional Reactive Programming
Araf Karsh Hamid
 
Reactive programming with rx java
Reactive programming with rx java
CongTrung Vnit
 
RxJS - The Reactive extensions for JavaScript
RxJS - The Reactive extensions for JavaScript
Viliam Elischer
 
Ad

More from Sperasoft (20)

особенности работы с Locomotion в Unreal Engine 4
особенности работы с Locomotion в Unreal Engine 4
Sperasoft
 
концепт и архитектура геймплея в Creach: The Depleted World
концепт и архитектура геймплея в Creach: The Depleted World
Sperasoft
 
Опыт разработки VR игры для UE4
Опыт разработки VR игры для UE4
Sperasoft
 
Организация работы с UE4 в команде до 20 человек
Организация работы с UE4 в команде до 20 человек
Sperasoft
 
Gameplay Tags
Gameplay Tags
Sperasoft
 
Data Driven Gameplay in UE4
Data Driven Gameplay in UE4
Sperasoft
 
Code and Memory Optimisation Tricks
Code and Memory Optimisation Tricks
Sperasoft
 
The theory of relational databases
The theory of relational databases
Sperasoft
 
Automated layout testing using Galen Framework
Automated layout testing using Galen Framework
Sperasoft
 
Sperasoft talks: Android Security Threats
Sperasoft talks: Android Security Threats
Sperasoft
 
Sperasoft‬ talks j point 2015
Sperasoft‬ talks j point 2015
Sperasoft
 
Effective Мeetings
Effective Мeetings
Sperasoft
 
Unreal Engine 4 Introduction
Unreal Engine 4 Introduction
Sperasoft
 
JIRA Development
JIRA Development
Sperasoft
 
Introduction to Elasticsearch
Introduction to Elasticsearch
Sperasoft
 
MOBILE DEVELOPMENT with HTML, CSS and JS
MOBILE DEVELOPMENT with HTML, CSS and JS
Sperasoft
 
Quick Intro Into Kanban
Quick Intro Into Kanban
Sperasoft
 
ECMAScript 6 Review
ECMAScript 6 Review
Sperasoft
 
Console Development in 15 minutes
Console Development in 15 minutes
Sperasoft
 
Database Indexes
Database Indexes
Sperasoft
 
особенности работы с Locomotion в Unreal Engine 4
особенности работы с Locomotion в Unreal Engine 4
Sperasoft
 
концепт и архитектура геймплея в Creach: The Depleted World
концепт и архитектура геймплея в Creach: The Depleted World
Sperasoft
 
Опыт разработки VR игры для UE4
Опыт разработки VR игры для UE4
Sperasoft
 
Организация работы с UE4 в команде до 20 человек
Организация работы с UE4 в команде до 20 человек
Sperasoft
 
Gameplay Tags
Gameplay Tags
Sperasoft
 
Data Driven Gameplay in UE4
Data Driven Gameplay in UE4
Sperasoft
 
Code and Memory Optimisation Tricks
Code and Memory Optimisation Tricks
Sperasoft
 
The theory of relational databases
The theory of relational databases
Sperasoft
 
Automated layout testing using Galen Framework
Automated layout testing using Galen Framework
Sperasoft
 
Sperasoft talks: Android Security Threats
Sperasoft talks: Android Security Threats
Sperasoft
 
Sperasoft‬ talks j point 2015
Sperasoft‬ talks j point 2015
Sperasoft
 
Effective Мeetings
Effective Мeetings
Sperasoft
 
Unreal Engine 4 Introduction
Unreal Engine 4 Introduction
Sperasoft
 
JIRA Development
JIRA Development
Sperasoft
 
Introduction to Elasticsearch
Introduction to Elasticsearch
Sperasoft
 
MOBILE DEVELOPMENT with HTML, CSS and JS
MOBILE DEVELOPMENT with HTML, CSS and JS
Sperasoft
 
Quick Intro Into Kanban
Quick Intro Into Kanban
Sperasoft
 
ECMAScript 6 Review
ECMAScript 6 Review
Sperasoft
 
Console Development in 15 minutes
Console Development in 15 minutes
Sperasoft
 
Database Indexes
Database Indexes
Sperasoft
 
Ad

Recently uploaded (20)

Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
The State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry Report
Liveplex
 
“From Enterprise to Makers: Driving Vision AI Innovation at the Extreme Edge,...
“From Enterprise to Makers: Driving Vision AI Innovation at the Extreme Edge,...
Edge AI and Vision Alliance
 
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
Muhammad Rizwan Akram
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
PyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent Integration
barqawicloud
 
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Alliance
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
Crypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdf
Stephen Perrenod
 
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Alliance
 
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
biswajitbanerjee38
 
MuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API Catalog
shyamraj55
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
Edge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdf
AmirStern2
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...
“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...
Edge AI and Vision Alliance
 
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Safe Software
 
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
NTT DATA Technology & Innovation
 
Data Validation and System Interoperability
Data Validation and System Interoperability
Safe Software
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
The State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry Report
Liveplex
 
“From Enterprise to Makers: Driving Vision AI Innovation at the Extreme Edge,...
“From Enterprise to Makers: Driving Vision AI Innovation at the Extreme Edge,...
Edge AI and Vision Alliance
 
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
Muhammad Rizwan Akram
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
PyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent Integration
barqawicloud
 
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Alliance
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
Crypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdf
Stephen Perrenod
 
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Alliance
 
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
biswajitbanerjee38
 
MuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API Catalog
shyamraj55
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
Edge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdf
AmirStern2
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...
“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...
Edge AI and Vision Alliance
 
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Safe Software
 
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
NTT DATA Technology & Innovation
 
Data Validation and System Interoperability
Data Validation and System Interoperability
Safe Software
 

Sperasoft Talks: RxJava Functional Reactive Programming on Android

  • 1. RxJava: Functional Reactive Programming on Android Alexey Chernin, Software Developer
  • 2. Based on: “What does it mean to be Reactive” - Erik Meijer “Rx-Fy all the things!” - Benjamin Augustin “RxJava Easy Wins” - Ron Shapiro “Android reactive programming with Rxjava” - Ivan Morgillo “Rx in 15 Minutes” - Erik Meijer “Functional Reactive Programming in the Netflix API” - Ben Christensen
  • 3. Based on: "RxJava Essentials" by Ivan Morgillo, May 2015 “Реактивный двигатель для вашего Android приложения” - Матвей Мальков https://github.com/ReactiveX/RxJava/wiki “Learning RxJava (for Android) by example” - Kaushik Gopal “Reactive Programming in Java 8 With RxJava” - Russell Elledge “Rx Workshop”
  • 4. Reactive Systems are:  Responsive: The system responds in a timely manner if at all possible.  Resilient: The system stays responsive in the face of failure.  Elastic: The system stays responsive under varying workload.  Message Driven: Reactive Systems rely on asynchronous message-passing to establish a boundary between components that ensures loose coupling, isolation, location transparency, and provides the means to delegate errors as messages. Published on September 16 2014. (v2.0) The Reactive Manifesto www.reactivemanifesto.org
  • 5. Functional reactive programming is an idea from the late 90s that inspired Erik Meijer, a computer scientist at Microsoft, to design and develop the Microsoft Rx library. From .NET to RxJava In 2012, at Netflix, they started to port .NET Rx to the JVM. With a post on the Netflix tech blog in February 2013, Ben Christensen and Jafar Husain showed RxJava to the world for the first time. “Reactive programming is a programming paradigm based on the concept of an asynchronous data flow. A data flow is like a river: it can be observed, filtered, manipulated, or merged with a second flow to create a new flow for a new consumer”. Ivan Morgillo
  • 6. Pure functions always returns the same result for a given set of parameter values.  No side effects caused by Class or Instance state.  No side effects caused by I/O devices.  No time related side effects. Pure functions
  • 8. • Store function as a variable • Pass a function as a parameter • Function can return a function  Composition  Lazy execution Pure functions: example 2
  • 9. Butter Knife by Jake Wharton
  • 11. Why Retrofit? https://instructure.github.io/blog/2013/12/09/volley-vs-retrofit Supports: • Gson - JSON serialization. • Simple - XML serialization. • OkHttp - HTTP client. • Robospice - asynchronous network requests. Fast: “Retrofit” - Jacob Tabak “A Few Ok Libraries” - Jake Wharton
  • 12. The old way o Extend AsyncTask to make HTTP request in background o Build the query string from array of NameValuePairs (12 lines) o Read InputStream into String (20 lines) o Parse JSON (75 lines)
  • 13. The rxjava-android module contains Android-specific bindings for RxJava. It adds a number of classes to RxJava to assist in writing reactive components in Android applications. o It provides a Scheduler that schedules an Observable on a given Android Handler thread, particularly the main UI thread. o It provides operators that make it easier to deal with Fragment and Activity life-cycle callbacks. o It provides wrappers for various Android messaging and notification components so that they can be lifted into an Rx call chain. o It provides reusable, self-contained, reactive components for common Android use cases and UI concerns. (coming soon). The RxJava Android Module
  • 14. Gradle and Maven Retrolambda Plugin
  • 16. o Observables and Iterables share a similar API. o Observable is the push equivalent of Iterable, which is pull. Iterable and Observable With Iterable, the consumer synchronously pulls values from the producer and the thread is blocked until these values arrive. By contrast, with Observable, the producer asynchronously pushes values to the Observer whenever values are available.
  • 17. The Observer pattern is the perfect fit for any of these scenarios: o When your architecture has two entities, one depending on the other, and you want to keep them separated to change them or reuse them independently. o When a changing object has to notify an unknown amount of related objects about its own o change. o When a changing object has to notify other objects without making assumptions about who these objects are. Observer pattern
  • 20. Subject A subject is a object that can be an Observable and an Observer at the same time. A subject can subscribe to an Observable, acting like an Observer, and it can emit new items or even pass through the item it received, acting like an Observable. RxJava provides four different types of subjects: o PublishSubject - emits all subsequently observed items to the subscriber, once an Observer has subscribed. o BehaviorSubject - emits the most recent item it has observed and all subsequent observed items to each subscribed Observer. o ReplaySubject - buffers all items it observes and replays them to any Observer that subscribes. o AsyncSubject - publishes only the last item observed to each Observer that has subscribed, when the source Observable completes.
  • 23. Observable creation: examples o Observable.just("one", "two", "three"); o Observable.just("one", "two", "three").repeat(3); o Observable.range(10, 3); - Takes two numbers as parameters: the first one is the starting point, and the second one is the amount of numbers we want to emit. o Observable.interval(3, TimeUnit.SECONDS); - Takes two parameters: a number that specifies the amount of time between two emissions, and the unit of time to be used. o Observable.timer(3, 3, TimeUnit.SECONDS); - Starts with an initial delay (3 seconds in the example) and then keeps on emitting a new number every N seconds (3 in the example).
  • 30. Filtering Observables Observable.just("one", "two", "three").filter((s)->{ return !s.equals("two"); });
  • 32. sample() creates a new Observable sequence that will emit the most recent item emitted by the Observable source in a decided time interval. Filtering Observables debounce() starts its internal timer, and if no new item is emitted during this timespan, the last item is emitted by the new Observable.
  • 39. Questions? Thank you for your attention