SlideShare a Scribd company logo
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
Reactive Programming Patterns with RxSwift
Base concepts
Asynchronous observable sequences
Base concepts
• Compose and transform observable sequences using
operators
• Rx models the asynchronous propagation of change
Reactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwift
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

More Related Content

What's hot (20)

Rxjs ppt
Rxjs pptRxjs ppt
Rxjs ppt
Christoffer Noring
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJS
Brainhub
 
Map kit light
Map kit lightMap kit light
Map kit light
CocoaHeads France
 
Oop assignment 02
Oop assignment 02Oop assignment 02
Oop assignment 02
MamoonKhan39
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScript
jnewmanux
 
Rxjs ngvikings
Rxjs ngvikingsRxjs ngvikings
Rxjs ngvikings
Christoffer Noring
 
Introduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaIntroduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoa
Florent Pillet
 
Luis Atencio on RxJS
Luis Atencio on RxJSLuis Atencio on RxJS
Luis Atencio on RxJS
Luis Atencio
 
RxJS Evolved
RxJS EvolvedRxJS Evolved
RxJS Evolved
trxcllnt
 
RxJS 5 in Depth
RxJS 5 in DepthRxJS 5 in Depth
RxJS 5 in Depth
C4Media
 
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
Egor Andreevich
 
Realm.io par Clement Sauvage
Realm.io par Clement SauvageRealm.io par Clement Sauvage
Realm.io par Clement Sauvage
CocoaHeads 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 tomorrow
Viliam Elischer
 
RxJS - The Reactive extensions for JavaScript
RxJS - The Reactive extensions for JavaScriptRxJS - The Reactive extensions for JavaScript
RxJS - The Reactive extensions for JavaScript
Viliam Elischer
 
Angular2 rxjs
Angular2 rxjsAngular2 rxjs
Angular2 rxjs
Christoffer Noring
 
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
Oswald 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 js
Thomas 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.js
cacois
 
Rxjs swetugg
Rxjs swetuggRxjs swetugg
Rxjs swetugg
Christoffer Noring
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJS
Brainhub
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScript
jnewmanux
 
Introduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaIntroduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoa
Florent Pillet
 
Luis Atencio on RxJS
Luis Atencio on RxJSLuis Atencio on RxJS
Luis Atencio on RxJS
Luis Atencio
 
RxJS Evolved
RxJS EvolvedRxJS Evolved
RxJS Evolved
trxcllnt
 
RxJS 5 in Depth
RxJS 5 in DepthRxJS 5 in Depth
RxJS 5 in Depth
C4Media
 
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
Egor Andreevich
 
Realm.io par Clement Sauvage
Realm.io par Clement SauvageRealm.io par Clement Sauvage
Realm.io par Clement Sauvage
CocoaHeads 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 tomorrow
Viliam Elischer
 
RxJS - The Reactive extensions for JavaScript
RxJS - The Reactive extensions for JavaScriptRxJS - The Reactive extensions for JavaScript
RxJS - The Reactive extensions for JavaScript
Viliam 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 RxJS
Oswald 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 js
Thomas 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.js
cacois
 

Similar to Reactive Programming Patterns with RxSwift (20)

RxSwift
RxSwiftRxSwift
RxSwift
Sally Ahmed
 
Introduction to reactive programming
Introduction to reactive programmingIntroduction to reactive programming
Introduction to reactive programming
Leapfrog Technology Inc.
 
Reactive programming
Reactive programmingReactive programming
Reactive programming
Jianbin LIN
 
Rx for Android & iOS by Harin Trivedi
Rx for Android & iOS  by Harin TrivediRx for Android & iOS  by Harin Trivedi
Rx for Android & iOS by Harin Trivedi
harintrivedi
 
Intro to Reactive Programming with Swift
Intro to Reactive Programming with SwiftIntro to Reactive Programming with Swift
Intro to Reactive Programming with Swift
xw92
 
10 things you didn't know about RxSwift
10 things you didn't know about RxSwift10 things you didn't know about RxSwift
10 things you didn't know about RxSwift
Ricardo Sánchez Sotres
 
Rx – reactive extensions
Rx – reactive extensionsRx – reactive extensions
Rx – reactive extensions
Voislav Mishevski
 
Prescribing RX Responsibly
Prescribing RX ResponsiblyPrescribing RX Responsibly
Prescribing RX Responsibly
Nareg Khoshafian
 
RxJava pour Android : présentation lors du GDG Android Montréal
RxJava pour Android : présentation lors du GDG Android MontréalRxJava pour Android : présentation lors du GDG Android Montréal
RxJava pour Android : présentation lors du GDG Android Montréal
Sidereo
 
Rx Swift
Rx SwiftRx Swift
Rx Swift
Vincenzo Favara
 
Introduction to Reactive programming
Introduction to Reactive programmingIntroduction to Reactive programming
Introduction to Reactive programming
Dwi Randy Herdinanto
 
RxJava@DAUG
RxJava@DAUGRxJava@DAUG
RxJava@DAUG
Maxim Volgin
 
Reactive Thinking in iOS Development - Pedro Piñera Buendía - Codemotion Amst...
Reactive Thinking in iOS Development - Pedro Piñera Buendía - Codemotion Amst...Reactive Thinking in iOS Development - Pedro Piñera Buendía - Codemotion Amst...
Reactive Thinking in iOS Development - Pedro Piñera Buendía - Codemotion Amst...
Codemotion
 
Practical MVVM Using RxSwift
Practical MVVM Using RxSwiftPractical MVVM Using RxSwift
Practical MVVM Using RxSwift
Mahmoud El-Naggar
 
Rx- Reactive Extensions for .NET
Rx- Reactive Extensions for .NETRx- Reactive Extensions for .NET
Rx- Reactive Extensions for .NET
Jakub Malý
 
Reactive programming with RxSwift
Reactive programming with RxSwiftReactive programming with RxSwift
Reactive programming with RxSwift
Oleksandr Stepanov
 
Microservices Part 4: Functional Reactive Programming
Microservices Part 4: Functional Reactive ProgrammingMicroservices Part 4: Functional Reactive Programming
Microservices Part 4: Functional Reactive Programming
Araf Karsh Hamid
 
Streams, Streams Everywhere! An Introduction to Rx
Streams, Streams Everywhere! An Introduction to RxStreams, Streams Everywhere! An Introduction to Rx
Streams, Streams Everywhere! An Introduction to Rx
Andrzej Sitek
 
[Rx] rx cocoa
[Rx] rx cocoa[Rx] rx cocoa
[Rx] rx cocoa
Moonbeom KWON
 
RxJS In-Depth - AngularConnect 2015
RxJS In-Depth - AngularConnect 2015RxJS In-Depth - AngularConnect 2015
RxJS In-Depth - AngularConnect 2015
Ben Lesh
 
Reactive programming
Reactive programmingReactive programming
Reactive programming
Jianbin LIN
 
Rx for Android & iOS by Harin Trivedi
Rx for Android & iOS  by Harin TrivediRx for Android & iOS  by Harin Trivedi
Rx for Android & iOS by Harin Trivedi
harintrivedi
 
Intro to Reactive Programming with Swift
Intro to Reactive Programming with SwiftIntro to Reactive Programming with Swift
Intro to Reactive Programming with Swift
xw92
 
Prescribing RX Responsibly
Prescribing RX ResponsiblyPrescribing RX Responsibly
Prescribing RX Responsibly
Nareg Khoshafian
 
RxJava pour Android : présentation lors du GDG Android Montréal
RxJava pour Android : présentation lors du GDG Android MontréalRxJava pour Android : présentation lors du GDG Android Montréal
RxJava pour Android : présentation lors du GDG Android Montréal
Sidereo
 
Introduction to Reactive programming
Introduction to Reactive programmingIntroduction to Reactive programming
Introduction to Reactive programming
Dwi Randy Herdinanto
 
Reactive Thinking in iOS Development - Pedro Piñera Buendía - Codemotion Amst...
Reactive Thinking in iOS Development - Pedro Piñera Buendía - Codemotion Amst...Reactive Thinking in iOS Development - Pedro Piñera Buendía - Codemotion Amst...
Reactive Thinking in iOS Development - Pedro Piñera Buendía - Codemotion Amst...
Codemotion
 
Practical MVVM Using RxSwift
Practical MVVM Using RxSwiftPractical MVVM Using RxSwift
Practical MVVM Using RxSwift
Mahmoud El-Naggar
 
Rx- Reactive Extensions for .NET
Rx- Reactive Extensions for .NETRx- Reactive Extensions for .NET
Rx- Reactive Extensions for .NET
Jakub Malý
 
Reactive programming with RxSwift
Reactive programming with RxSwiftReactive programming with RxSwift
Reactive programming with RxSwift
Oleksandr Stepanov
 
Microservices Part 4: Functional Reactive Programming
Microservices Part 4: Functional Reactive ProgrammingMicroservices Part 4: Functional Reactive Programming
Microservices Part 4: Functional Reactive Programming
Araf Karsh Hamid
 
Streams, Streams Everywhere! An Introduction to Rx
Streams, Streams Everywhere! An Introduction to RxStreams, Streams Everywhere! An Introduction to Rx
Streams, Streams Everywhere! An Introduction to Rx
Andrzej Sitek
 
RxJS In-Depth - AngularConnect 2015
RxJS In-Depth - AngularConnect 2015RxJS In-Depth - AngularConnect 2015
RxJS In-Depth - AngularConnect 2015
Ben Lesh
 
Ad

Recently uploaded (20)

Artificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across IndustriesArtificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across Industries
SandeepKS52
 
FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025
Safe Software
 
How Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines OperationsHow Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines Operations
Insurance Tech Services
 
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlowDevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
Aarno Aukia
 
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The SequelMarketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
BradBedford3
 
Top 5 Task Management Software to Boost Productivity in 2025
Top 5 Task Management Software to Boost Productivity in 2025Top 5 Task Management Software to Boost Productivity in 2025
Top 5 Task Management Software to Boost Productivity in 2025
Orangescrum
 
Who will create the languages of the future?
Who will create the languages of the future?Who will create the languages of the future?
Who will create the languages of the future?
Jordi Cabot
 
14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework
Angelo Theodorou
 
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Wondershare PDFelement Pro 11.4.20.3548 Crack Free DownloadWondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Puppy jhon
 
GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?
felipeceotto
 
IBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - IntroductionIBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - Introduction
Gaurav Sharma
 
Migrating to Azure Cosmos DB the Right Way
Migrating to Azure Cosmos DB the Right WayMigrating to Azure Cosmos DB the Right Way
Migrating to Azure Cosmos DB the Right Way
Alexander (Alex) Komyagin
 
Maximizing Business Value with AWS Consulting Services.pdf
Maximizing Business Value with AWS Consulting Services.pdfMaximizing Business Value with AWS Consulting Services.pdf
Maximizing Business Value with AWS Consulting Services.pdf
Elena Mia
 
Software Testing & it’s types (DevOps)
Software  Testing & it’s  types (DevOps)Software  Testing & it’s  types (DevOps)
Software Testing & it’s types (DevOps)
S Pranav (Deepu)
 
COBOL Programming with VSCode - IBM Certificate
COBOL Programming with VSCode - IBM CertificateCOBOL Programming with VSCode - IBM Certificate
COBOL Programming with VSCode - IBM Certificate
VICTOR MAESTRE RAMIREZ
 
Automating Map Production With FME and Python
Automating Map Production With FME and PythonAutomating Map Production With FME and Python
Automating Map Production With FME and Python
Safe Software
 
wAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptxwAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptx
SimonedeGijt
 
Porting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 WebinarPorting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 Webinar
ICS
 
How the US Navy Approaches DevSecOps with Raise 2.0
How the US Navy Approaches DevSecOps with Raise 2.0How the US Navy Approaches DevSecOps with Raise 2.0
How the US Navy Approaches DevSecOps with Raise 2.0
Anchore
 
Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3
Gaurav Sharma
 
Artificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across IndustriesArtificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across Industries
SandeepKS52
 
FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025
Safe Software
 
How Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines OperationsHow Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines Operations
Insurance Tech Services
 
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlowDevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
Aarno Aukia
 
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The SequelMarketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
BradBedford3
 
Top 5 Task Management Software to Boost Productivity in 2025
Top 5 Task Management Software to Boost Productivity in 2025Top 5 Task Management Software to Boost Productivity in 2025
Top 5 Task Management Software to Boost Productivity in 2025
Orangescrum
 
Who will create the languages of the future?
Who will create the languages of the future?Who will create the languages of the future?
Who will create the languages of the future?
Jordi Cabot
 
14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework
Angelo Theodorou
 
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Wondershare PDFelement Pro 11.4.20.3548 Crack Free DownloadWondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Puppy jhon
 
GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?
felipeceotto
 
IBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - IntroductionIBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - Introduction
Gaurav Sharma
 
Maximizing Business Value with AWS Consulting Services.pdf
Maximizing Business Value with AWS Consulting Services.pdfMaximizing Business Value with AWS Consulting Services.pdf
Maximizing Business Value with AWS Consulting Services.pdf
Elena Mia
 
Software Testing & it’s types (DevOps)
Software  Testing & it’s  types (DevOps)Software  Testing & it’s  types (DevOps)
Software Testing & it’s types (DevOps)
S Pranav (Deepu)
 
COBOL Programming with VSCode - IBM Certificate
COBOL Programming with VSCode - IBM CertificateCOBOL Programming with VSCode - IBM Certificate
COBOL Programming with VSCode - IBM Certificate
VICTOR MAESTRE RAMIREZ
 
Automating Map Production With FME and Python
Automating Map Production With FME and PythonAutomating Map Production With FME and Python
Automating Map Production With FME and Python
Safe Software
 
wAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptxwAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptx
SimonedeGijt
 
Porting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 WebinarPorting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 Webinar
ICS
 
How the US Navy Approaches DevSecOps with Raise 2.0
How the US Navy Approaches DevSecOps with Raise 2.0How the US Navy Approaches DevSecOps with Raise 2.0
How the US Navy Approaches DevSecOps with Raise 2.0
Anchore
 
Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3
Gaurav Sharma
 
Ad

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
  • 6. Base concepts • Compose and transform observable sequences using operators • Rx models the asynchronous propagation of change
  • 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