SlideShare uma empresa Scribd logo
1 de 28
Rx
by
Harin Trivedi
Sr. Software Engineer
➔ Multiple threads
➔ Nested background
tasks
➔ UI blocking
➔ Memory leaks
Common problems
➔ Combining results
from background task
➔ Retrying background
tasks
➔ Backpressure
(identified in v2)
Rx = ReactiveX = Reactive Extensions
➔ ReactiveX is a library for composing asynchronous and event-
based programs by using observable sequences.
➔ It extends the observer pattern to support sequences of data
and/or events and adds operators that allow you to compose
sequences together declaratively while abstracting away
concerns about things like low-level threading, synchronization,
thread-safety, concurrent data structures, and non-blocking I/O
The Difference:
Functional reactive programming operates on values that
change continuously over time, while ReactiveX operates
on discrete values that are emitted over time
Functional Programming
+
Reactive Programming
Rx
=
OBSERVABLE
+
OBSERVER
+
SCHEDULERS
OBSERVA
BLE
OBSER
VER
SCHEDULE
R
OPERAT
ORS
➔ ANDROID (Rx-Java2)
➔ iOS (Rx-Swift3)
GETTING STARTED ...
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
compile 'io.reactivex.rxjava2:rxjava:2.0.1'
# Podfile
target 'YOUR_TARGET_NAME' do
pod 'RxSwift', '~> 2.0 / 3.0'
pod 'RxCocoa', '~> 2.0 / 3.0'
end
Before we start ...
WHAT ARE OPERATORS ?
➔ Items emitted by an Observable can be transformed, modified, and
filtered through Operators before notifying the subscribed Observer
object(s).
➔ Applying an Operator typically returns another Observable as a result,
which is convenient as this allows us to chain multiple operations to
obtain a desired result
➔ Eg. just(), from(), map(), filter(), combine() etc.
OPERATORS (400+)
Input
1. Creating Observables : just, from
2. Transforming Observables : map, flatMap
3. Filtering Observables : first, last, filter
4. Combining Observables : join, merge
Output
1. Error Handling Operators : catch, retry
2. Observable Utility Operators : observeOn, subscribeOn, timeout
3. Conditional and Boolean Operators : skipUntil, takeUntil
4. Mathematical and Aggregate Operators : max, min, sum
5. Backpressure Operators
6. Connectable Observable Operators
http://reactivex.io/documentation/operators.htm
➔ ANDROID
➔ iOS
1. Create an Observable
//Observable. This will emit single data
Observable<String> observable = Observable.just("Item 1");
//Observable. This will emit sequence of the data
Observable<String> observable = Observable.fromArray(new String[]{"1", "2", "3", "4"})
//Observable. This will emit single data
let observable = Observable.just("Item 1");
//Observable. This will emit sequence of the data
let observable = Observable.from(["1", "2", "3", "4"])
Observer is notified with three events when data is emitted by the observable
stream:
1. Observer #onNext(T)— invoked when an item is emitted from the stream
2. Observable #onError(Throwable)— invoked when an error has occurred within
the stream
3. Observable #onCompleted()— invoked when the stream is finished emitting
items.
2. Create an Observer & Schedule it
Example
Observer<String> observer = new
Observer<String>() {
@Override
public void onCompleted() {..}
@Override
public void onError(Throwable e) {..}
@Override
public void onNext(String s) {..}
};
observable.subscribe(observer);
1.let subscription = observable.subscribe {
event in
switch event {
case .next(let value):
print(value)
case .error(let error):
print(error)
case .completed:
print("completed")
}
}
2.let sub = observable.subscribe
(onNext:{ print($0) })
➔ Android ➔ iOS
Do you want to play with more
operators?
Marble Diagram
Example 1 : map()
➔ Android ➔ iOS
Observable<Integer> observable =
Observable.fromArray(1, 2, 3, 4)
observable..map(new
Function<Integer, Integer>() {
public Integer apply(Integer num){
return num * num;
}
}).subscribe(observer);
let observable =
Observable.from([1, 2, 3, 4])
let sub =
observable.map {$0 * $0}
.subscribe
(onNext:{
print($0)
})
OUTPUT: 1 4 9 16
Example 2 : filter()
➔ Android ➔ iOS
Observable<Integer> observable =
Observable.fromArray(20, 10, 5, 40)
observable.filter(new
Predicate<Integer>() {
public boolean test(Integer num) {
return num > 10;
}
}).subscribe(observer);
let observable =
Observable.from([20, 10, 5, 40])
let sub =
observable.filter {$0 > 10}
.subscribe
(onNext:{
print($0)
})
OUTPUT: 30 22 60
Example 3 : concat()
➔ Android ➔ iOS
Observable<Integer> observable1 =
Observable.fromArray(1, 2, 3, 4)
Observable<Integer> observable2 =
Observable.fromArray(10, 20, 30, 40)
observable.concat(
observable1,observable2)
.subscribe(observer);
let observable1 =
Observable.from([1, 2, 3, 4])
let observable2 =
Observable.from([10, 20, 30, 40])
Observable.of(observable1,observable2)
.concat().subscribe(onNext:{
print($0)
})
OUTPUT : 1 2 3 4 10 20 30 40
Subjects
“A Subject is a sort of bridge or proxy that acts both as an
observer and as an Observable. Because it is an observer, it
can subscribe to one or more Observables, and because it is
an Observable, it can pass through the items it observes, and
reemit them or emit new items.”
➔ PublishSubject
Emits to an observer only those items that are emitted by the source
Observable(s)
➔ ReplaySubject
Emits to any observer all of the items that were emitted by the source
Observable(s)
Example 4 : Publish Subject & merge()
➔ Android ➔ iOS
PublishSubject<Integer> source =
PublishSubject.create();
PublishSubject<Integer> source2 =
PublishSubject.create();
ObservablePublish.merge(source,source2).
subscribe(observer);
source.onNext(1);
source2.onNext(20);
source.onNext(2);
source2.onNext(10);
let publish1 = PublishSubject<Int>()
let publish2 = PublishSubject<Int>()
Observable.of(publish1,publish2).merge()
.subscribe(onNext:{
print($0)
})
publish1.onNext(1);
publish2.onNext(20);
publish1.onNext(2);
publish3.onNext(10);
OUTPUT: 1 20 2 10
Example 5 : zip()
➔ Android
PublishSubject<String> s1 =
PublishSubject.create();
PublishSubject<Integer> s2 =
PublishSubject.create();
ObservablePublish.zip(s1, s2, new
BiFunction<String, Integer, String>() {
public String apply(Integer a, String b) {
return a+"-"+b;
}
}).subscribe(observer);
s1.onNext(“City 1”);
s1.onNext(“City 2”);
s2.onNext(22);
s2.onNext(25);
➔ iOS
let s1 = PublishSubject<String>()
let s2 = PublishSubject<Int>()
Observable<(String,Int)>.zip(s1, s2)
{ (a, b) throws -> (String,Int) in
return (a,b)
}.subscribe {
print("($0.element!.0) -($0.element!.1)")
}
s1.onNext(“City 1”);
s1.onNext(“City 2”);
s2.onNext(22);
s2.onNext(25);
OUTPUT : City 1 - 22, City 2 - 25
In Rx, concurrency is managed by the Scheduler, when you want to perform
multithreading with multiple streams and also operate on UI thread
simultaneously.
Main example of threads are
1. Computational Thread
2. I/O Thread
3. UI Thread
Scheduler
➔ subscribeOn() : By using this method you can define on which thread the
observable should run.
➔ observeOn() : By using this method you can define on which thread the
observer should run.
Manage Subscription
CompositeDisposable mSubscription = new CompositeDisposable();
...
mSubscription.add(disposable1); //Add disposable 1
mSubscription.add(disposable2); //Add disposable 2
...
public void onDestroy() {
//Unsubscribe both subscriptions.
mSubscription.dispose();
}
//disposable1.dispose(); also works
➔ Composite Subscriptions
➔ Unsubscribe Subscriptions
Custom Action / Method
Observable
.map(
new Function<List<ApiUser>,List<User>>() {
public List<User> apply(
List<ApiUser> apiUsers)
{
return // List<User>
}
}).subscribe(observer);
// BiFunction
Observable<Array<Int>>
.map {
(val) -> Array<String> in
return // Array<String>
}.subscribe(
onNext:
{
print($0)
})
(val1, val2) -> //Resulting type
➔ Android ➔ iOS
// Todo
➔ Pipeline
➔ Parallel flow
➔ Flowable (Backpressure in Rxjava2)
➔ Disposable
➔ RxBus
And more...
References:
Official guides:
➔ http://reactivex.io/intro.html
➔ http://reactivex.io/tutorials.html
➔ https://github.com/ReactiveX/RxJava
➔ https://github.com/ReactiveX/RxAndroid
➔ https://github.com/ReactiveX/RxSwift
Tutorials:
➔ https://realm.io/news/gotocph-jake-wharton-exploring-rxjava2-android/
➔ https://medium.com/@kevalpatel2106/what-is-reactive-programming-da37c1611382
➔ https://android.jlelse.eu/introduction-to-rxjava-for-android-b15e0ba1b338
➔ https://android.jlelse.eu/what-should-you-know-about-rx-operators-54716a16b310
➔ https://www.raywenderlich.com/158026/introducing-rxswift-reactive-programming-swift
➔ https://www.raywenderlich.com/138547/getting-started-with-rxswift-and-rxcocoa
➔ https://medium.com/ios-os-x-development/learn-and-master-%EF%B8%8F-the-basics-of-rxswift-
in-10-minutes-818ea6e0a05b
➔ https://medium.com/3xplore/handling-api-calls-using-retrofit-2-and-rxjava-2-1871c891b6ae
➔ https://github.com/square/retrofit/tree/master/retrofit-adapters/rxjava2
➔ https://github.com/RxSwiftCommunity/RxAlamofire
➔ http://rxmarbles.com/
References:
MY DEMO:
➔ https://github.com/HarinTrivedi/RxJava2Retrofit2Demo-master
➔ https://github.com/HarinTrivedi/RxSwiftAlamofireDemo-master
MVP for ios:
➔ https://medium.com/ios-os-x-development/ios-architecture-patterns-ecba4c38de52
➔ https://blog.moove-it.com/going-from-mvc-to-mvp-on-ios/
➔ https://github.com/iyadagha/iOS-mvp-sample/tree/master/TestMVP
➔ https://github.com/SeptiyanAndika/MVP-Swift/tree/master/MVP-Swift
Thank you
- Harin Trivedi

Mais conteúdo relacionado

Mais procurados

A Playful Introduction to Rx
A Playful Introduction to RxA Playful Introduction to Rx
A Playful Introduction to RxAndrey Cheptsov
 
Understanding reactive programming with microsoft reactive extensions
Understanding reactive programming  with microsoft reactive extensionsUnderstanding reactive programming  with microsoft reactive extensions
Understanding reactive programming with microsoft reactive extensionsOleksandr Zhevzhyk
 
[xp2013] Narrow Down What to Test
[xp2013] Narrow Down What to Test[xp2013] Narrow Down What to Test
[xp2013] Narrow Down What to TestZsolt Fabok
 
Using Fuzzy Code Search to Link Code Fragments in Discussions to Source Code
Using Fuzzy Code Search to Link Code Fragments in Discussions to Source CodeUsing Fuzzy Code Search to Link Code Fragments in Discussions to Source Code
Using Fuzzy Code Search to Link Code Fragments in Discussions to Source CodeNicolas Bettenburg
 
An Introduction to RxJava
An Introduction to RxJavaAn Introduction to RxJava
An Introduction to RxJavaSanjay Acharya
 
Reactive programming with tracker
Reactive programming with trackerReactive programming with tracker
Reactive programming with trackerDesignveloper
 
C# console programms
C# console programmsC# console programms
C# console programmsYasir Khan
 
Hacking the Mesh: Extending Istio with WebAssembly Modules | DevNation Tech Talk
Hacking the Mesh: Extending Istio with WebAssembly Modules | DevNation Tech TalkHacking the Mesh: Extending Istio with WebAssembly Modules | DevNation Tech Talk
Hacking the Mesh: Extending Istio with WebAssembly Modules | DevNation Tech TalkRed Hat Developers
 
(1) c sharp introduction_basics_dot_net
(1) c sharp introduction_basics_dot_net(1) c sharp introduction_basics_dot_net
(1) c sharp introduction_basics_dot_netNico Ludwig
 
Taking advantage of the Amazon Web Services (AWS) Family
Taking advantage of the Amazon Web Services (AWS) FamilyTaking advantage of the Amazon Web Services (AWS) Family
Taking advantage of the Amazon Web Services (AWS) FamilyBen Hall
 
Intro to RxJava/RxAndroid - GDG Munich Android
Intro to RxJava/RxAndroid - GDG Munich AndroidIntro to RxJava/RxAndroid - GDG Munich Android
Intro to RxJava/RxAndroid - GDG Munich AndroidEgor Andreevich
 

Mais procurados (17)

A Playful Introduction to Rx
A Playful Introduction to RxA Playful Introduction to Rx
A Playful Introduction to Rx
 
Understanding reactive programming with microsoft reactive extensions
Understanding reactive programming  with microsoft reactive extensionsUnderstanding reactive programming  with microsoft reactive extensions
Understanding reactive programming with microsoft reactive extensions
 
[xp2013] Narrow Down What to Test
[xp2013] Narrow Down What to Test[xp2013] Narrow Down What to Test
[xp2013] Narrow Down What to Test
 
Forgive me for i have allocated
Forgive me for i have allocatedForgive me for i have allocated
Forgive me for i have allocated
 
AWS Java SDK @ scale
AWS Java SDK @ scaleAWS Java SDK @ scale
AWS Java SDK @ scale
 
Using Fuzzy Code Search to Link Code Fragments in Discussions to Source Code
Using Fuzzy Code Search to Link Code Fragments in Discussions to Source CodeUsing Fuzzy Code Search to Link Code Fragments in Discussions to Source Code
Using Fuzzy Code Search to Link Code Fragments in Discussions to Source Code
 
An Introduction to RxJava
An Introduction to RxJavaAn Introduction to RxJava
An Introduction to RxJava
 
Reactive Extensions
Reactive ExtensionsReactive Extensions
Reactive Extensions
 
Code red SUM
Code red SUMCode red SUM
Code red SUM
 
Reactive programming with tracker
Reactive programming with trackerReactive programming with tracker
Reactive programming with tracker
 
C# console programms
C# console programmsC# console programms
C# console programms
 
C# labprograms
C# labprogramsC# labprograms
C# labprograms
 
Hacking the Mesh: Extending Istio with WebAssembly Modules | DevNation Tech Talk
Hacking the Mesh: Extending Istio with WebAssembly Modules | DevNation Tech TalkHacking the Mesh: Extending Istio with WebAssembly Modules | DevNation Tech Talk
Hacking the Mesh: Extending Istio with WebAssembly Modules | DevNation Tech Talk
 
(1) c sharp introduction_basics_dot_net
(1) c sharp introduction_basics_dot_net(1) c sharp introduction_basics_dot_net
(1) c sharp introduction_basics_dot_net
 
Rxjava meetup presentation
Rxjava meetup presentationRxjava meetup presentation
Rxjava meetup presentation
 
Taking advantage of the Amazon Web Services (AWS) Family
Taking advantage of the Amazon Web Services (AWS) FamilyTaking advantage of the Amazon Web Services (AWS) Family
Taking advantage of the Amazon Web Services (AWS) Family
 
Intro to RxJava/RxAndroid - GDG Munich Android
Intro to RxJava/RxAndroid - GDG Munich AndroidIntro to RxJava/RxAndroid - GDG Munich Android
Intro to RxJava/RxAndroid - GDG Munich Android
 

Semelhante a Rx for Android & iOS by Harin Trivedi

Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on AndroidTomáš Kypta
 
RxJava2 Slides
RxJava2 SlidesRxJava2 Slides
RxJava2 SlidesYarikS
 
RxJava 2 Reactive extensions for the JVM
RxJava 2  Reactive extensions for the JVMRxJava 2  Reactive extensions for the JVM
RxJava 2 Reactive extensions for the JVMNetesh Kumar
 
Intro to Reactive Thinking and RxJava 2
Intro to Reactive Thinking and RxJava 2Intro to Reactive Thinking and RxJava 2
Intro to Reactive Thinking and RxJava 2JollyRogers5
 
Programming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidProgramming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidEmanuele Di Saverio
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaRick Warren
 
The Mayans Lost Guide to RxJava on Android
The Mayans Lost Guide to RxJava on AndroidThe Mayans Lost Guide to RxJava on Android
The Mayans Lost Guide to RxJava on AndroidFernando Cejas
 
Akka.NET streams and reactive streams
Akka.NET streams and reactive streamsAkka.NET streams and reactive streams
Akka.NET streams and reactive streamsBartosz Sypytkowski
 
Functional Reactive Programming (FRP): Working with RxJS
Functional Reactive Programming (FRP): Working with RxJSFunctional Reactive Programming (FRP): Working with RxJS
Functional Reactive Programming (FRP): Working with RxJSOswald Campesato
 
Processing large-scale graphs with Google(TM) Pregel by MICHAEL HACKSTEIN at...
 Processing large-scale graphs with Google(TM) Pregel by MICHAEL HACKSTEIN at... Processing large-scale graphs with Google(TM) Pregel by MICHAEL HACKSTEIN at...
Processing large-scale graphs with Google(TM) Pregel by MICHAEL HACKSTEIN at...Big Data Spain
 
Przywitaj się z reactive extensions
Przywitaj się z reactive extensionsPrzywitaj się z reactive extensions
Przywitaj się z reactive extensionsMarcin Juraszek
 
Demystifying Reactive Programming
Demystifying Reactive ProgrammingDemystifying Reactive Programming
Demystifying Reactive ProgrammingTom Bulatewicz, PhD
 
Functional Reactive Programming on Android
Functional Reactive Programming on AndroidFunctional Reactive Programming on Android
Functional Reactive Programming on AndroidSam Lee
 
Programming with ZooKeeper - A basic tutorial
Programming with ZooKeeper - A basic tutorialProgramming with ZooKeeper - A basic tutorial
Programming with ZooKeeper - A basic tutorialJeff Smith
 
Swift & ReactiveX – Asynchronous Event-Based Funsies with RxSwift
Swift & ReactiveX – Asynchronous Event-Based Funsies with RxSwiftSwift & ReactiveX – Asynchronous Event-Based Funsies with RxSwift
Swift & ReactiveX – Asynchronous Event-Based Funsies with RxSwiftAaron Douglas
 

Semelhante a Rx for Android & iOS by Harin Trivedi (20)

RxAndroid
RxAndroidRxAndroid
RxAndroid
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on Android
 
RxJava2 Slides
RxJava2 SlidesRxJava2 Slides
RxJava2 Slides
 
Saving lives with rx java
Saving lives with rx javaSaving lives with rx java
Saving lives with rx java
 
RxJava 2 Reactive extensions for the JVM
RxJava 2  Reactive extensions for the JVMRxJava 2  Reactive extensions for the JVM
RxJava 2 Reactive extensions for the JVM
 
Intro to Reactive Thinking and RxJava 2
Intro to Reactive Thinking and RxJava 2Intro to Reactive Thinking and RxJava 2
Intro to Reactive Thinking and RxJava 2
 
Programming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidProgramming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for Android
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
 
The Mayans Lost Guide to RxJava on Android
The Mayans Lost Guide to RxJava on AndroidThe Mayans Lost Guide to RxJava on Android
The Mayans Lost Guide to RxJava on Android
 
Akka.NET streams and reactive streams
Akka.NET streams and reactive streamsAkka.NET streams and reactive streams
Akka.NET streams and reactive streams
 
RxSubject And Operators
RxSubject And OperatorsRxSubject And Operators
RxSubject And Operators
 
Functional Reactive Programming (FRP): Working with RxJS
Functional Reactive Programming (FRP): Working with RxJSFunctional Reactive Programming (FRP): Working with RxJS
Functional Reactive Programming (FRP): Working with RxJS
 
Processing large-scale graphs with Google(TM) Pregel by MICHAEL HACKSTEIN at...
 Processing large-scale graphs with Google(TM) Pregel by MICHAEL HACKSTEIN at... Processing large-scale graphs with Google(TM) Pregel by MICHAEL HACKSTEIN at...
Processing large-scale graphs with Google(TM) Pregel by MICHAEL HACKSTEIN at...
 
Przywitaj się z reactive extensions
Przywitaj się z reactive extensionsPrzywitaj się z reactive extensions
Przywitaj się z reactive extensions
 
Demystifying Reactive Programming
Demystifying Reactive ProgrammingDemystifying Reactive Programming
Demystifying Reactive Programming
 
Functional Reactive Programming on Android
Functional Reactive Programming on AndroidFunctional Reactive Programming on Android
Functional Reactive Programming on Android
 
JAX-RS 2.1 Reloaded @ Devoxx
JAX-RS 2.1 Reloaded @ DevoxxJAX-RS 2.1 Reloaded @ Devoxx
JAX-RS 2.1 Reloaded @ Devoxx
 
Programming with ZooKeeper - A basic tutorial
Programming with ZooKeeper - A basic tutorialProgramming with ZooKeeper - A basic tutorial
Programming with ZooKeeper - A basic tutorial
 
RxJava@Android
RxJava@AndroidRxJava@Android
RxJava@Android
 
Swift & ReactiveX – Asynchronous Event-Based Funsies with RxSwift
Swift & ReactiveX – Asynchronous Event-Based Funsies with RxSwiftSwift & ReactiveX – Asynchronous Event-Based Funsies with RxSwift
Swift & ReactiveX – Asynchronous Event-Based Funsies with RxSwift
 

Último

Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 

Último (20)

Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 

Rx for Android & iOS by Harin Trivedi

  • 2. ➔ Multiple threads ➔ Nested background tasks ➔ UI blocking ➔ Memory leaks Common problems ➔ Combining results from background task ➔ Retrying background tasks ➔ Backpressure (identified in v2)
  • 3. Rx = ReactiveX = Reactive Extensions ➔ ReactiveX is a library for composing asynchronous and event- based programs by using observable sequences. ➔ It extends the observer pattern to support sequences of data and/or events and adds operators that allow you to compose sequences together declaratively while abstracting away concerns about things like low-level threading, synchronization, thread-safety, concurrent data structures, and non-blocking I/O
  • 4. The Difference: Functional reactive programming operates on values that change continuously over time, while ReactiveX operates on discrete values that are emitted over time Functional Programming + Reactive Programming
  • 8. ➔ ANDROID (Rx-Java2) ➔ iOS (Rx-Swift3) GETTING STARTED ... compile 'io.reactivex.rxjava2:rxandroid:2.0.1' compile 'io.reactivex.rxjava2:rxjava:2.0.1' # Podfile target 'YOUR_TARGET_NAME' do pod 'RxSwift', '~> 2.0 / 3.0' pod 'RxCocoa', '~> 2.0 / 3.0' end
  • 9. Before we start ... WHAT ARE OPERATORS ? ➔ Items emitted by an Observable can be transformed, modified, and filtered through Operators before notifying the subscribed Observer object(s). ➔ Applying an Operator typically returns another Observable as a result, which is convenient as this allows us to chain multiple operations to obtain a desired result ➔ Eg. just(), from(), map(), filter(), combine() etc.
  • 10. OPERATORS (400+) Input 1. Creating Observables : just, from 2. Transforming Observables : map, flatMap 3. Filtering Observables : first, last, filter 4. Combining Observables : join, merge Output 1. Error Handling Operators : catch, retry 2. Observable Utility Operators : observeOn, subscribeOn, timeout 3. Conditional and Boolean Operators : skipUntil, takeUntil 4. Mathematical and Aggregate Operators : max, min, sum 5. Backpressure Operators 6. Connectable Observable Operators http://reactivex.io/documentation/operators.htm
  • 11. ➔ ANDROID ➔ iOS 1. Create an Observable //Observable. This will emit single data Observable<String> observable = Observable.just("Item 1"); //Observable. This will emit sequence of the data Observable<String> observable = Observable.fromArray(new String[]{"1", "2", "3", "4"}) //Observable. This will emit single data let observable = Observable.just("Item 1"); //Observable. This will emit sequence of the data let observable = Observable.from(["1", "2", "3", "4"])
  • 12. Observer is notified with three events when data is emitted by the observable stream: 1. Observer #onNext(T)— invoked when an item is emitted from the stream 2. Observable #onError(Throwable)— invoked when an error has occurred within the stream 3. Observable #onCompleted()— invoked when the stream is finished emitting items. 2. Create an Observer & Schedule it
  • 13. Example Observer<String> observer = new Observer<String>() { @Override public void onCompleted() {..} @Override public void onError(Throwable e) {..} @Override public void onNext(String s) {..} }; observable.subscribe(observer); 1.let subscription = observable.subscribe { event in switch event { case .next(let value): print(value) case .error(let error): print(error) case .completed: print("completed") } } 2.let sub = observable.subscribe (onNext:{ print($0) }) ➔ Android ➔ iOS
  • 14.
  • 15. Do you want to play with more operators? Marble Diagram
  • 16. Example 1 : map() ➔ Android ➔ iOS Observable<Integer> observable = Observable.fromArray(1, 2, 3, 4) observable..map(new Function<Integer, Integer>() { public Integer apply(Integer num){ return num * num; } }).subscribe(observer); let observable = Observable.from([1, 2, 3, 4]) let sub = observable.map {$0 * $0} .subscribe (onNext:{ print($0) }) OUTPUT: 1 4 9 16
  • 17. Example 2 : filter() ➔ Android ➔ iOS Observable<Integer> observable = Observable.fromArray(20, 10, 5, 40) observable.filter(new Predicate<Integer>() { public boolean test(Integer num) { return num > 10; } }).subscribe(observer); let observable = Observable.from([20, 10, 5, 40]) let sub = observable.filter {$0 > 10} .subscribe (onNext:{ print($0) }) OUTPUT: 30 22 60
  • 18. Example 3 : concat() ➔ Android ➔ iOS Observable<Integer> observable1 = Observable.fromArray(1, 2, 3, 4) Observable<Integer> observable2 = Observable.fromArray(10, 20, 30, 40) observable.concat( observable1,observable2) .subscribe(observer); let observable1 = Observable.from([1, 2, 3, 4]) let observable2 = Observable.from([10, 20, 30, 40]) Observable.of(observable1,observable2) .concat().subscribe(onNext:{ print($0) }) OUTPUT : 1 2 3 4 10 20 30 40
  • 19. Subjects “A Subject is a sort of bridge or proxy that acts both as an observer and as an Observable. Because it is an observer, it can subscribe to one or more Observables, and because it is an Observable, it can pass through the items it observes, and reemit them or emit new items.” ➔ PublishSubject Emits to an observer only those items that are emitted by the source Observable(s) ➔ ReplaySubject Emits to any observer all of the items that were emitted by the source Observable(s)
  • 20. Example 4 : Publish Subject & merge() ➔ Android ➔ iOS PublishSubject<Integer> source = PublishSubject.create(); PublishSubject<Integer> source2 = PublishSubject.create(); ObservablePublish.merge(source,source2). subscribe(observer); source.onNext(1); source2.onNext(20); source.onNext(2); source2.onNext(10); let publish1 = PublishSubject<Int>() let publish2 = PublishSubject<Int>() Observable.of(publish1,publish2).merge() .subscribe(onNext:{ print($0) }) publish1.onNext(1); publish2.onNext(20); publish1.onNext(2); publish3.onNext(10); OUTPUT: 1 20 2 10
  • 21. Example 5 : zip() ➔ Android PublishSubject<String> s1 = PublishSubject.create(); PublishSubject<Integer> s2 = PublishSubject.create(); ObservablePublish.zip(s1, s2, new BiFunction<String, Integer, String>() { public String apply(Integer a, String b) { return a+"-"+b; } }).subscribe(observer); s1.onNext(“City 1”); s1.onNext(“City 2”); s2.onNext(22); s2.onNext(25); ➔ iOS let s1 = PublishSubject<String>() let s2 = PublishSubject<Int>() Observable<(String,Int)>.zip(s1, s2) { (a, b) throws -> (String,Int) in return (a,b) }.subscribe { print("($0.element!.0) -($0.element!.1)") } s1.onNext(“City 1”); s1.onNext(“City 2”); s2.onNext(22); s2.onNext(25); OUTPUT : City 1 - 22, City 2 - 25
  • 22. In Rx, concurrency is managed by the Scheduler, when you want to perform multithreading with multiple streams and also operate on UI thread simultaneously. Main example of threads are 1. Computational Thread 2. I/O Thread 3. UI Thread Scheduler ➔ subscribeOn() : By using this method you can define on which thread the observable should run. ➔ observeOn() : By using this method you can define on which thread the observer should run.
  • 23. Manage Subscription CompositeDisposable mSubscription = new CompositeDisposable(); ... mSubscription.add(disposable1); //Add disposable 1 mSubscription.add(disposable2); //Add disposable 2 ... public void onDestroy() { //Unsubscribe both subscriptions. mSubscription.dispose(); } //disposable1.dispose(); also works ➔ Composite Subscriptions ➔ Unsubscribe Subscriptions
  • 24. Custom Action / Method Observable .map( new Function<List<ApiUser>,List<User>>() { public List<User> apply( List<ApiUser> apiUsers) { return // List<User> } }).subscribe(observer); // BiFunction Observable<Array<Int>> .map { (val) -> Array<String> in return // Array<String> }.subscribe( onNext: { print($0) }) (val1, val2) -> //Resulting type ➔ Android ➔ iOS
  • 25. // Todo ➔ Pipeline ➔ Parallel flow ➔ Flowable (Backpressure in Rxjava2) ➔ Disposable ➔ RxBus And more...
  • 26. References: Official guides: ➔ http://reactivex.io/intro.html ➔ http://reactivex.io/tutorials.html ➔ https://github.com/ReactiveX/RxJava ➔ https://github.com/ReactiveX/RxAndroid ➔ https://github.com/ReactiveX/RxSwift Tutorials: ➔ https://realm.io/news/gotocph-jake-wharton-exploring-rxjava2-android/ ➔ https://medium.com/@kevalpatel2106/what-is-reactive-programming-da37c1611382 ➔ https://android.jlelse.eu/introduction-to-rxjava-for-android-b15e0ba1b338 ➔ https://android.jlelse.eu/what-should-you-know-about-rx-operators-54716a16b310 ➔ https://www.raywenderlich.com/158026/introducing-rxswift-reactive-programming-swift ➔ https://www.raywenderlich.com/138547/getting-started-with-rxswift-and-rxcocoa ➔ https://medium.com/ios-os-x-development/learn-and-master-%EF%B8%8F-the-basics-of-rxswift- in-10-minutes-818ea6e0a05b ➔ https://medium.com/3xplore/handling-api-calls-using-retrofit-2-and-rxjava-2-1871c891b6ae ➔ https://github.com/square/retrofit/tree/master/retrofit-adapters/rxjava2 ➔ https://github.com/RxSwiftCommunity/RxAlamofire ➔ http://rxmarbles.com/
  • 27. References: MY DEMO: ➔ https://github.com/HarinTrivedi/RxJava2Retrofit2Demo-master ➔ https://github.com/HarinTrivedi/RxSwiftAlamofireDemo-master MVP for ios: ➔ https://medium.com/ios-os-x-development/ios-architecture-patterns-ecba4c38de52 ➔ https://blog.moove-it.com/going-from-mvc-to-mvp-on-ios/ ➔ https://github.com/iyadagha/iOS-mvp-sample/tree/master/TestMVP ➔ https://github.com/SeptiyanAndika/MVP-Swift/tree/master/MVP-Swift
  • 28. Thank you - Harin Trivedi