SlideShare une entreprise Scribd logo
1  sur  38
Télécharger pour lire hors ligne
Reactive Programming Patterns
with RxSwift
Florent Pillet — @fpillet
FrenchKit Conference Paris — September 23rd, 2016
Agenda
• Introduction to Rx
• Creating observable sequences
• Basic patterns
• User interface patterns
• Architecture patterns
About Rx
• Microsoft Reactive Extensions (Rx.NET) - 2009
• ReactiveX.io defines a common API for Rx implementations
• RxSwift 2015
• Shares concepts and API with other implementations
• Heavily tested framework
Base concepts
Asynchronous observable sequences
Base concepts
• Compose and transform observable sequences using
operators
• Rx models the asynchronous propagation of change
What did we just see?
• a sequence emitted one item then completed,
• the map operator transformed a sequence of JSON objects
into a sequence of Floats,
• similar to Swift sequence mapping but asynchronous.
What did we just see?
Experiment with interactive marble diagrams
at rxmarbles.com
Observable sequence lifecycle
let disposable = someObservable.subscribe(
onNext: { print("value: ($0)") },
onCompleted: { print("completed") },
)
Observable sequence lifecycle
let disposable = someObservable.subscribe(
onNext: { print("value: ($0)") },
onError: { print("error ($0)") },
onCompleted: { print("completed") }
)
Observable sequence lifecycle
let disposable = someObservable.subscribe(
onNext: { print("value: ($0)") },
onError: { print("error ($0)") },
onCompleted: { print("completed") },
onDisposed: { print("disposed") }
)
// at any point, cancel your subscription
// by calling dispose()
disposable.dispose()
The mysterious genesis of the Observable
The mysterious genesis of the Observable
RxCocoa
import RxCocoa
let disposable = NSNotificationCenter.defaultCenter()
.rx_notification(UIApplicationSignificantTimeChangeNotification)
.subscribeNext {
(notification: UINotification) in
print("Date changed: time to update!")
}
The mysterious genesis of the
Observable
RxCocoa
import RxCocoa
@IBOutlet var textField : UITextField!
override func viewDidLoad() {
super.viewDidLoad()
let _ = textField.rx_text.subscribeNext {
(text: String) in
print("text field changed to (text)")
}
}
The mysterious genesis of the
Observable
Manual creation
let strings : Observable<Int> =
Observable.create { observer in
observer.onNext("Hello")
observer.onNext("World")
observer.onCompleted()
// we don't need to release any
// resource on dispose()
return NopDisposable.instance
}
The mysterious genesis of the Observable
Manual creation
let asyncComputation : Observable<Data> =
Observable.create { observer in
let task = someAsyncTask()
task.run(
success: {
(result: Data) in
observer.onNext(result)
observer.onCompleted()
}
error: {
(error: ErrorType) in
observer.onError(error)
}
)
return AnonymousDisposable {
task.cancel()
}
}
The mysterious genesis of the Observable
More ways to obtain observables:
• Items from an array or collection
• DelegateProxy
• rx_observe(type, keypath, options)
• rx_sentMessage(#selector)
• Subject (stateless) and Variable (stateful)
Basic Patterns
Composition
Task: update temperature label when button tapped
func getTemperature(city: String)
-> Observable<(String,Float)>
func formattedTemperature(temp: Float)
-> String
let disposable = button.rx_tap
.withLatestFrom(textField.rx_text)
.flatMapLatest {
(city: String) -> Observable<(String,Float)> in
return getTemperature(city)
}
.subscribeNext {
(temp: (String,Float)) in
let degrees = formattedTemperature(temp.1)
label.text = "It's (degrees) in (temp.0)"
}
Aggregation
Task: obtain the current temperature in multiple cities
let disposable = ["Berlin","London",
"Madrid","Paris",
"Rome"]
.map {
(city: String) -> Observable<(String,Float)> in
return getTemperature(city)
}
.toObservable()
.merge()
.toArray()
.subscribeNext {
(temperatures: [(String,Float)]) in
// we get the result of the five requests
// at once in a nice array!
}
Cancellation
Task: update temperature every second until VC disappears
var timerDisposable : Disposable!
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
timerDisposable = Observable
.timer(0.0, period: 60.0, scheduler: MainScheduler.instance)
.flatMap { _ -> Observable<String> in
getTemperature("Paris").map {
(temp: (String,Float)) -> String in
return String(temp.1)
}
}
.bindTo(label.rx_text)
}
override func viewWillDisappear(animated: Bool) {
timerDisposable.dispose()
super.viewWillDisappear(animated)
}
Error handling
Task: if a temperature network request fails, display "--"
func getTemperatureAsString(city: String) -> Observable<(String,String)> {
return getTemperature(city)
.map {
(temp: (String,Float)) -> String in
return (city, formattedTemperature(temp.1))
}
.catchErrorJustReturn((city, "--"))
}
Error handling
Task: if a temperature network request fails, display "--"
let disposable = button.rx_tap
.withLatestFrom(textField.rx_text)
.flatMapLatest {
(city: String) -> Observable<(String,String)> in
return getTemperatureAsString(city)
}
.map {
(temp: (String,String)) -> String in
return "It's (temp.1) in (temp.0)"
}
.bindTo(label.rx_text)
User interface
patterns
Driver
let disposable = button.rx_tap
.withLatestFrom(textField.rx_text)
.flatMapLatest {
(city: String) -> Driver<String> in
return getTemperature(city)
.map { formattedTemperature($0.1) }
.asDriver(onErrorJustReturn: "--")
}
.drive(label.rx_text)
Action
• not technically part of RxSwift
• an important pattern for binding the UI
• pod Action
• a very useful pattern for MVVM
Action
import Action
lazy var getTemperatureAction : CocoaAction = CocoaAction {
[unowned self] in
return self.getTemperatureAsString(self.textfield.text)
}
button.rx_action = getTemperatureAction
getTemperatureAction.elements.bindTo(label.rx_text)
Architecture patterns
Architecture patterns
• Expose all data to display as Observable sequences
• Use Action to wire up the UI whenever possible
• MVVM is a perfect fit for Rx
Architecture patterns
• Decouple application logic from application infrastructure
• Storage, geolocation, network requests, image cache etc.
are a good fit for insulation
• Makes replacing whole parts of the app easier
• Testing and mocking are easier too
Summary
Reactive programming
• Powerful way to express program logic
• Model the asynchronous propagation of change
• Eliminate state from your code
• Code is more testable
• RxSwift is a solid foundation
• Fast growing pool of users, add-ons and contributors
(RxSwiftCommunity!)
Links
• RxSwift source github.com/reactivex/rxswift
• Community projects github.com/RxSwiftCommunity
• Artsy's Eidolon app github.com/artsy/eidolon
• ReactiveX website reactivex.io
• RxMarbles rxmarbles.com
Q & A

Contenu connexe

Tendances

Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJSBrainhub
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptjnewmanux
 
Introduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaIntroduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaFlorent Pillet
 
Luis Atencio on RxJS
Luis Atencio on RxJSLuis Atencio on RxJS
Luis Atencio on RxJSLuis Atencio
 
RxJS Evolved
RxJS EvolvedRxJS Evolved
RxJS Evolvedtrxcllnt
 
RxJS 5 in Depth
RxJS 5 in DepthRxJS 5 in Depth
RxJS 5 in DepthC4Media
 
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
 
Realm.io par Clement Sauvage
Realm.io par Clement SauvageRealm.io par Clement Sauvage
Realm.io par Clement SauvageCocoaHeads France
 
RxJS101 - What you need to know to get started with RxJS tomorrow
RxJS101 - What you need to know to get started with RxJS tomorrowRxJS101 - What you need to know to get started with RxJS tomorrow
RxJS101 - What you need to know to get started with RxJS tomorrowViliam Elischer
 
RxJS - The Reactive extensions for JavaScript
RxJS - The Reactive extensions for JavaScriptRxJS - The Reactive extensions for JavaScript
RxJS - The Reactive extensions for JavaScriptViliam Elischer
 
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
 
Callbacks and control flow in Node js
Callbacks and control flow in Node jsCallbacks and control flow in Node js
Callbacks and control flow in Node jsThomas Roch
 
You will learn RxJS in 2017
You will learn RxJS in 2017You will learn RxJS in 2017
You will learn RxJS in 2017名辰 洪
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jscacois
 

Tendances (20)

Rxjs ppt
Rxjs pptRxjs ppt
Rxjs ppt
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJS
 
Map kit light
Map kit lightMap kit light
Map kit light
 
Oop assignment 02
Oop assignment 02Oop assignment 02
Oop assignment 02
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScript
 
Rxjs ngvikings
Rxjs ngvikingsRxjs ngvikings
Rxjs ngvikings
 
Introduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaIntroduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoa
 
Luis Atencio on RxJS
Luis Atencio on RxJSLuis Atencio on RxJS
Luis Atencio on RxJS
 
RxJS Evolved
RxJS EvolvedRxJS Evolved
RxJS Evolved
 
RxJS 5 in Depth
RxJS 5 in DepthRxJS 5 in Depth
RxJS 5 in Depth
 
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
 
Realm.io par Clement Sauvage
Realm.io par Clement SauvageRealm.io par Clement Sauvage
Realm.io par Clement Sauvage
 
RxJS101 - What you need to know to get started with RxJS tomorrow
RxJS101 - What you need to know to get started with RxJS tomorrowRxJS101 - What you need to know to get started with RxJS tomorrow
RxJS101 - What you need to know to get started with RxJS tomorrow
 
RxJS - The Reactive extensions for JavaScript
RxJS - The Reactive extensions for JavaScriptRxJS - The Reactive extensions for JavaScript
RxJS - The Reactive extensions for JavaScript
 
Angular2 rxjs
Angular2 rxjsAngular2 rxjs
Angular2 rxjs
 
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
 
Callbacks and control flow in Node js
Callbacks and control flow in Node jsCallbacks and control flow in Node js
Callbacks and control flow in Node js
 
You will learn RxJS in 2017
You will learn RxJS in 2017You will learn RxJS in 2017
You will learn RxJS in 2017
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
 
Rxjs swetugg
Rxjs swetuggRxjs swetugg
Rxjs swetugg
 

Similaire à Reactive Programming Patterns with RxSwift

Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSAdam L Barrett
 
RESTful API using scalaz (3)
RESTful API using scalaz (3)RESTful API using scalaz (3)
RESTful API using scalaz (3)Yeshwanth Kumar
 
Wprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
Wprowadzenie do technologii Big Data / Intro to Big Data EcosystemWprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
Wprowadzenie do technologii Big Data / Intro to Big Data EcosystemSages
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on AndroidTomáš Kypta
 
The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)jeffz
 
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash courseCodepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash courseSages
 
GDG Devfest 2019 - Build go kit microservices at kubernetes with ease
GDG Devfest 2019 - Build go kit microservices at kubernetes with easeGDG Devfest 2019 - Build go kit microservices at kubernetes with ease
GDG Devfest 2019 - Build go kit microservices at kubernetes with easeKAI CHU CHUNG
 
Introduction to Spark with Scala
Introduction to Spark with ScalaIntroduction to Spark with Scala
Introduction to Spark with ScalaHimanshu Gupta
 
Swift - One step forward from Obj-C
Swift -  One step forward from Obj-CSwift -  One step forward from Obj-C
Swift - One step forward from Obj-CNissan Tsafrir
 
Asynchronous web apps with the Play Framework 2.0
Asynchronous web apps with the Play Framework 2.0Asynchronous web apps with the Play Framework 2.0
Asynchronous web apps with the Play Framework 2.0Oscar Renalias
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
 
Introduction to Scalding and Monoids
Introduction to Scalding and MonoidsIntroduction to Scalding and Monoids
Introduction to Scalding and MonoidsHugo Gävert
 
Node.js - async for the rest of us.
Node.js - async for the rest of us.Node.js - async for the rest of us.
Node.js - async for the rest of us.Mike Brevoort
 
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...GeeksLab Odessa
 
Wprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache HadoopWprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache HadoopSages
 

Similaire à Reactive Programming Patterns with RxSwift (20)

Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
 
RESTful API using scalaz (3)
RESTful API using scalaz (3)RESTful API using scalaz (3)
RESTful API using scalaz (3)
 
Rx workshop
Rx workshopRx workshop
Rx workshop
 
Rxjs marble-testing
Rxjs marble-testingRxjs marble-testing
Rxjs marble-testing
 
Hw09 Hadoop + Clojure
Hw09   Hadoop + ClojureHw09   Hadoop + Clojure
Hw09 Hadoop + Clojure
 
Hadoop + Clojure
Hadoop + ClojureHadoop + Clojure
Hadoop + Clojure
 
Wprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
Wprowadzenie do technologii Big Data / Intro to Big Data EcosystemWprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
Wprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on Android
 
The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)
 
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash courseCodepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
 
GDG Devfest 2019 - Build go kit microservices at kubernetes with ease
GDG Devfest 2019 - Build go kit microservices at kubernetes with easeGDG Devfest 2019 - Build go kit microservices at kubernetes with ease
GDG Devfest 2019 - Build go kit microservices at kubernetes with ease
 
Introduction to Spark with Scala
Introduction to Spark with ScalaIntroduction to Spark with Scala
Introduction to Spark with Scala
 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011
 
Swift - One step forward from Obj-C
Swift -  One step forward from Obj-CSwift -  One step forward from Obj-C
Swift - One step forward from Obj-C
 
Asynchronous web apps with the Play Framework 2.0
Asynchronous web apps with the Play Framework 2.0Asynchronous web apps with the Play Framework 2.0
Asynchronous web apps with the Play Framework 2.0
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
Introduction to Scalding and Monoids
Introduction to Scalding and MonoidsIntroduction to Scalding and Monoids
Introduction to Scalding and Monoids
 
Node.js - async for the rest of us.
Node.js - async for the rest of us.Node.js - async for the rest of us.
Node.js - async for the rest of us.
 
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
 
Wprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache HadoopWprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache Hadoop
 

Dernier

The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is insideshinachiaurasa2
 
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
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastPapp Krisztián
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfonteinmasabamasaba
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...masabamasaba
 
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
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...masabamasaba
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Hararemasabamasaba
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdfPearlKirahMaeRagusta1
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Harnessing ChatGPT - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT  - Elevating Productivity in Today's Agile EnvironmentHarnessing ChatGPT  - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT - Elevating Productivity in Today's Agile EnvironmentVictorSzoltysek
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...SelfMade bd
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2
 
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
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfkalichargn70th171
 
tonesoftg
tonesoftgtonesoftg
tonesoftglanshi9
 

Dernier (20)

The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
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-...
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
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 🔝✔️✔️
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Harnessing ChatGPT - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT  - Elevating Productivity in Today's Agile EnvironmentHarnessing ChatGPT  - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT - Elevating Productivity in Today's Agile Environment
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
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
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 

Reactive Programming Patterns with RxSwift

  • 1. Reactive Programming Patterns with RxSwift Florent Pillet — @fpillet FrenchKit Conference Paris — September 23rd, 2016
  • 2. Agenda • Introduction to Rx • Creating observable sequences • Basic patterns • User interface patterns • Architecture patterns
  • 3. About Rx • Microsoft Reactive Extensions (Rx.NET) - 2009 • ReactiveX.io defines a common API for Rx implementations • RxSwift 2015 • Shares concepts and API with other implementations • Heavily tested framework
  • 4.
  • 6. Base concepts • Compose and transform observable sequences using operators • Rx models the asynchronous propagation of change
  • 7.
  • 8.
  • 9.
  • 10.
  • 11. What did we just see? • a sequence emitted one item then completed, • the map operator transformed a sequence of JSON objects into a sequence of Floats, • similar to Swift sequence mapping but asynchronous.
  • 12. What did we just see? Experiment with interactive marble diagrams at rxmarbles.com
  • 13. Observable sequence lifecycle let disposable = someObservable.subscribe( onNext: { print("value: ($0)") }, onCompleted: { print("completed") }, )
  • 14. Observable sequence lifecycle let disposable = someObservable.subscribe( onNext: { print("value: ($0)") }, onError: { print("error ($0)") }, onCompleted: { print("completed") } )
  • 15. Observable sequence lifecycle let disposable = someObservable.subscribe( onNext: { print("value: ($0)") }, onError: { print("error ($0)") }, onCompleted: { print("completed") }, onDisposed: { print("disposed") } ) // at any point, cancel your subscription // by calling dispose() disposable.dispose()
  • 16. The mysterious genesis of the Observable
  • 17. The mysterious genesis of the Observable RxCocoa import RxCocoa let disposable = NSNotificationCenter.defaultCenter() .rx_notification(UIApplicationSignificantTimeChangeNotification) .subscribeNext { (notification: UINotification) in print("Date changed: time to update!") }
  • 18. The mysterious genesis of the Observable RxCocoa import RxCocoa @IBOutlet var textField : UITextField! override func viewDidLoad() { super.viewDidLoad() let _ = textField.rx_text.subscribeNext { (text: String) in print("text field changed to (text)") } }
  • 19. The mysterious genesis of the Observable Manual creation let strings : Observable<Int> = Observable.create { observer in observer.onNext("Hello") observer.onNext("World") observer.onCompleted() // we don't need to release any // resource on dispose() return NopDisposable.instance }
  • 20. The mysterious genesis of the Observable Manual creation let asyncComputation : Observable<Data> = Observable.create { observer in let task = someAsyncTask() task.run( success: { (result: Data) in observer.onNext(result) observer.onCompleted() } error: { (error: ErrorType) in observer.onError(error) } ) return AnonymousDisposable { task.cancel() } }
  • 21. The mysterious genesis of the Observable More ways to obtain observables: • Items from an array or collection • DelegateProxy • rx_observe(type, keypath, options) • rx_sentMessage(#selector) • Subject (stateless) and Variable (stateful)
  • 23. Composition Task: update temperature label when button tapped func getTemperature(city: String) -> Observable<(String,Float)> func formattedTemperature(temp: Float) -> String let disposable = button.rx_tap .withLatestFrom(textField.rx_text) .flatMapLatest { (city: String) -> Observable<(String,Float)> in return getTemperature(city) } .subscribeNext { (temp: (String,Float)) in let degrees = formattedTemperature(temp.1) label.text = "It's (degrees) in (temp.0)" }
  • 24. Aggregation Task: obtain the current temperature in multiple cities let disposable = ["Berlin","London", "Madrid","Paris", "Rome"] .map { (city: String) -> Observable<(String,Float)> in return getTemperature(city) } .toObservable() .merge() .toArray() .subscribeNext { (temperatures: [(String,Float)]) in // we get the result of the five requests // at once in a nice array! }
  • 25. Cancellation Task: update temperature every second until VC disappears var timerDisposable : Disposable! override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) timerDisposable = Observable .timer(0.0, period: 60.0, scheduler: MainScheduler.instance) .flatMap { _ -> Observable<String> in getTemperature("Paris").map { (temp: (String,Float)) -> String in return String(temp.1) } } .bindTo(label.rx_text) } override func viewWillDisappear(animated: Bool) { timerDisposable.dispose() super.viewWillDisappear(animated) }
  • 26. Error handling Task: if a temperature network request fails, display "--" func getTemperatureAsString(city: String) -> Observable<(String,String)> { return getTemperature(city) .map { (temp: (String,Float)) -> String in return (city, formattedTemperature(temp.1)) } .catchErrorJustReturn((city, "--")) }
  • 27. Error handling Task: if a temperature network request fails, display "--" let disposable = button.rx_tap .withLatestFrom(textField.rx_text) .flatMapLatest { (city: String) -> Observable<(String,String)> in return getTemperatureAsString(city) } .map { (temp: (String,String)) -> String in return "It's (temp.1) in (temp.0)" } .bindTo(label.rx_text)
  • 29. Driver let disposable = button.rx_tap .withLatestFrom(textField.rx_text) .flatMapLatest { (city: String) -> Driver<String> in return getTemperature(city) .map { formattedTemperature($0.1) } .asDriver(onErrorJustReturn: "--") } .drive(label.rx_text)
  • 30. Action • not technically part of RxSwift • an important pattern for binding the UI • pod Action • a very useful pattern for MVVM
  • 31. Action import Action lazy var getTemperatureAction : CocoaAction = CocoaAction { [unowned self] in return self.getTemperatureAsString(self.textfield.text) } button.rx_action = getTemperatureAction getTemperatureAction.elements.bindTo(label.rx_text)
  • 33. Architecture patterns • Expose all data to display as Observable sequences • Use Action to wire up the UI whenever possible • MVVM is a perfect fit for Rx
  • 34. Architecture patterns • Decouple application logic from application infrastructure • Storage, geolocation, network requests, image cache etc. are a good fit for insulation • Makes replacing whole parts of the app easier • Testing and mocking are easier too
  • 36. Reactive programming • Powerful way to express program logic • Model the asynchronous propagation of change • Eliminate state from your code • Code is more testable • RxSwift is a solid foundation • Fast growing pool of users, add-ons and contributors (RxSwiftCommunity!)
  • 37. Links • RxSwift source github.com/reactivex/rxswift • Community projects github.com/RxSwiftCommunity • Artsy's Eidolon app github.com/artsy/eidolon • ReactiveX website reactivex.io • RxMarbles rxmarbles.com
  • 38. Q & A