SlideShare a Scribd company logo
1 of 47
Download to read offline
SWIFT & REACTIVEX
Asynchronous Event-Based Funsies with RxSwift
WHO I AM
➤ Aaron Douglas
➤ Milwaukee, WI USA
➤ Mobile Maker for Automattic
(WordPress.com)
➤ Remote full time 3+ years
➤ @astralbodies
REACTIVE?

FUNCTIONAL?

MEH?
FUNCTIONAL & REACTIVE PROGRAMMING
➤ Reactive Programming
➤ Asynchronous Data Flow
➤ Functional Programming
➤ Map, Reduce, Filter
➤ Avoiding State
➤ Immutable Data
➤ Declarative Paradigm - logic of computation rather than describing flow
➤ Implementations - ReactiveCocoa/RAC, RxSwift
WHAT IS RXSWIFT?
WHAT IS RXSWIFT?
➤ Based on ReactiveX
➤ Many different ports: Java, JavaScript, .NET, Scala, Clojure, Swift, Kotlin, PHP, …
➤ Extends the Observer Pattern
➤ Related to Iterable Pattern
➤ Swift itself provides some protocols with equivalence
➤ SequenceType
➤ GeneratorType
OBSERVER PATTERN
NSNOTIFICATIONCENTER
NSNotificationCenter
.defaultCenter()
.addObserver(self,
selector:"downloadImage:",
name: "BLDownloadImageNotification",
object: nil)
NSNotificationCenter
.defaultCenter()
.postNotificationName("BLDownloadImageNotification",
object: self,
userInfo: ["imageView":
coverImage, "coverUrl": albumCover])
OBSERVER PATTERN
9
ITERATOR PATTERN
ITERATOR PATTERN
GENERATORS, SEQUENCES,
OH MY!
GENERATORS
public protocol GeneratorType {
associatedtype Element
public mutating func next() -> Self.Element?
}
GENERATORS
class CountdownGenerator: GeneratorType {
typealias Element = Int
var element: Element
init<T>(array: [T]) {
self.element = array.count
}
func next() -> Element? {
guard element > 0 else { return nil }
element -= 1
return element
}
}
let xs = ["A", "B", "C"]
let generator = CountdownGenerator(array: xs)
while let i = generator.next() {
print("Element (i) of the array is (xs[i])")
}
Element 2 of the array is C
Element 1 of the array is B
Element 0 of the array is A
SEQUENCES
public protocol SequenceType {
associatedtype Generator : GeneratorType
public func generate() -> Self.Generator
}
SEQUENCES
class ReverseSequence<T>: SequenceType {
var array: [T]
init(array: [T]) {
self.array = array
}
func generate() -> CountdownGenerator {
return CountdownGenerator(array: array)
}
}
let reverseSequence = ReverseSequence(array: xs)
let reverseGenerator = reverseSequence.generate()
while let i = reverseGenerator.next() {
print("Index (i) is (xs[i])")
}
for i in ReverseSequence(array: xs) {
print("Index (i) is (xs[i])")
}
Index 2 is C
Index 1 is B
Index 0 is A
Index 2 is C
Index 1 is B
Index 0 is A
OBSERVABLES
OBSERVERTYPE
public protocol ObserverType {
associatedtype E
func on(event: Event<E>)
}
public enum Event<Element> {
case Next(Element)
case Error(ErrorType)
case Completed
}
OBSERVABLETYPE
public protocol ObservableType : ObservableConvertibleType {
associatedtype E
func subscribe<O: ObserverType where O.E == E>(observer: O) -> Disposable
}
public protocol ObservableConvertibleType {
associatedtype E
func asObservable() -> Observable<E>
}
VISUALIZATIONS OF SEQUENCES
--1--2--3--4--5--6--| // terminates normally
--a--b--a--a--a---d---X // terminates with error
---tap-tap-------tap---> // infinite; never ends
MAKING AN OBSERVABLE
let disposeBag = DisposeBag()
Observable.just("X")
.subscribe { event in
print(event)
}
.addDisposableTo(disposeBag)
MAKING AN OBSERVABLE
let disposeBag = DisposeBag()
Observable.of("W", "X", "Y", "X")
.subscribeNext { element in
print(element)
}
.addDisposableTo(disposeBag)
MAKING AN OBSERVABLE
let disposeBag = DisposeBag()
["W", "X", "Y", "Z"].toObservable()
.subscribeNext { print($0) }
.addDisposableTo(disposeBag)
SUBSCRIBING
someObservable.subscribe(
onNext: { print("Element: ", $0) },
onError: { print("Error: ", $0) },
onCompleted: { print("Completed") },
onDisposed: { print("Disposed") }
)
someObservable
.subscribeNext {
print("Element: ", $0)
}
OPERATORS
MAP
MAP
let disposeBag = DisposeBag()
Observable.of(1, 2, 3)
.map { $0 * 10 }
.subscribeNext { print($0) }
.addDisposableTo(disposeBag)
---
10
20
30
FILTER
FILTER
let disposeBag = DisposeBag()
Observable.of(2, 30, 22, 5, 60, 1)
.filter { $0 > 10 }
.subscribeNext { print($0) }
.addDisposableTo(disposeBag)
---
30
22
60
SCAN
SCAN
let disposeBag = DisposeBag()
Observable.of(1, 2, 3, 4, 5)
.scan(0) { aggregateValue, newValue in
aggregateValue + newValue
}
.subscribeNext { print($0) }
.addDisposableTo(disposeBag)
---
1
3
6
10
15
MERGE
MERGE
let disposeBag = DisposeBag()
let subject1 = PublishSubject<String>()
let subject2 = PublishSubject<String>()
Observable.of(subject1, subject2)
.merge()
.subscribeNext { print($0) }
.addDisposableTo(disposeBag)
subject1.onNext("20")
subject1.onNext("40")
subject1.onNext("60")
subject2.onNext("1")
subject1.onNext("80")
subject1.onNext("100")
subject2.onNext("1")
20
40
60
1
80
100
1
RXMARBLES.COM
DISPOSING
.dispose()
.addDisposableTo(disposeBag)
COCOA + RXSWIFT
BINDINGS
totCountStepper
.rx_value
.subscribeNext { value in
self.totalNumberOfTots.value = Int(value)
}
.addDisposableTo(disposeBag)
BINDINGS
➤ NSTextStorage
➤ UIActivityIndicatorView
➤ UIAlertAction
➤ UIApplication
➤ UIBarButtonItem
➤ UIButton
➤ UICollectionView
➤ UIControl
➤ UIDatePicker
➤ UIGestureRecognizer
➤ UIImagePickerController
➤ UIImageView
➤ UILabel
➤ UINavigationItem
➤ UIPageControl
➤ UIPickerView
➤ UIProgressView
➤ UIRefreshControl
➤ UIScrollView
➤ UISearchBar
➤ UISearchController
➤ UISegmentedControl
➤ UISlider
➤ UIStepper
➤ UISwitch
➤ UITabBar
➤ UITabBarItem
➤ UITableView
➤ UITextField
➤ UITextView
➤ UIView
➤ UIViewController
AN EXAMPLE
TATER TOT TIMER
RXSWIFT IN THE WILD
WHERE TO LEARN MORE
WHERE TO LEARN MORE
➤ ReactiveX RxSwift main repo
➤ https://github.com/ReactiveX/RxSwift/
➤ FRP iOS Learning Resources
➤ https://gist.github.com/JaviLorbada/4a7bd6129275ebefd5a6
➤ Functional Reactive Programming with RxSwift
➤ https://realm.io/news/slug-max-alexander-functional-reactive-rxswift/
➤ RxSwift Slack
➤ http://rxswift-slack.herokuapp.com/
AARON DOUGLAS@astralbodies
http://astralbodi.es

More Related Content

What's hot

Intro to Java 8 Closures (Dainius Mezanskas)
Intro to Java 8 Closures (Dainius Mezanskas)Intro to Java 8 Closures (Dainius Mezanskas)
Intro to Java 8 Closures (Dainius Mezanskas)
Kaunas Java User Group
 
Functional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event SystemsFunctional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event Systems
Leonardo Borges
 

What's hot (20)

Oop assignment 02
Oop assignment 02Oop assignment 02
Oop assignment 02
 
Rxjs ngvikings
Rxjs ngvikingsRxjs ngvikings
Rxjs ngvikings
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScript
 
Reactive, component 그리고 angular2
Reactive, component 그리고  angular2Reactive, component 그리고  angular2
Reactive, component 그리고 angular2
 
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
 
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
 
Swift Sequences & Collections
Swift Sequences & CollectionsSwift Sequences & Collections
Swift Sequences & Collections
 
Luis Atencio on RxJS
Luis Atencio on RxJSLuis Atencio on RxJS
Luis Atencio on RxJS
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
 
Introduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaIntroduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoa
 
My Gentle Introduction to RxJS
My Gentle Introduction to RxJSMy Gentle Introduction to RxJS
My Gentle Introduction to RxJS
 
An Introduction to Reactive Cocoa
An Introduction to Reactive CocoaAn Introduction to Reactive Cocoa
An Introduction to Reactive Cocoa
 
Reactive cocoa made Simple with Swift
Reactive cocoa made Simple with SwiftReactive cocoa made Simple with Swift
Reactive cocoa made Simple with Swift
 
Intro to Java 8 Closures (Dainius Mezanskas)
Intro to Java 8 Closures (Dainius Mezanskas)Intro to Java 8 Closures (Dainius Mezanskas)
Intro to Java 8 Closures (Dainius Mezanskas)
 
You will learn RxJS in 2017
You will learn RxJS in 2017You will learn RxJS in 2017
You will learn RxJS in 2017
 
Functional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event SystemsFunctional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event Systems
 
Map kit light
Map kit lightMap kit light
Map kit light
 
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
 
Javascript Execution Context Flow
Javascript Execution Context FlowJavascript Execution Context Flow
Javascript Execution Context Flow
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
 

Similar to Swift & ReactiveX – Asynchronous Event-Based Funsies with RxSwift

Reactive extensions itjam
Reactive extensions itjamReactive extensions itjam
Reactive extensions itjam
Ciklum Ukraine
 
rx.js make async programming simpler
rx.js make async programming simplerrx.js make async programming simpler
rx.js make async programming simpler
Alexander Mostovenko
 

Similar to Swift & ReactiveX – Asynchronous Event-Based Funsies with RxSwift (20)

Reactive programming
Reactive programmingReactive programming
Reactive programming
 
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
 
Reactive Java (GeeCON 2014)
Reactive Java (GeeCON 2014)Reactive Java (GeeCON 2014)
Reactive Java (GeeCON 2014)
 
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...
 
Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...
 
Reactive Programming in Java by Mario Fusco - Codemotion Rome 2015
Reactive Programming in Java by Mario Fusco - Codemotion Rome 2015Reactive Programming in Java by Mario Fusco - Codemotion Rome 2015
Reactive Programming in Java by Mario Fusco - Codemotion Rome 2015
 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011
 
Server side JavaScript: going all the way
Server side JavaScript: going all the wayServer side JavaScript: going all the way
Server side JavaScript: going all the way
 
RxJava2 Slides
RxJava2 SlidesRxJava2 Slides
RxJava2 Slides
 
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...
 
Declarative presentations UIKonf
Declarative presentations UIKonfDeclarative presentations UIKonf
Declarative presentations UIKonf
 
Reactive extensions itjam
Reactive extensions itjamReactive extensions itjam
Reactive extensions itjam
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on Android
 
Rx java in action
Rx java in actionRx java in action
Rx java in action
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJS
 
How to Think in RxJava Before Reacting
How to Think in RxJava Before ReactingHow to Think in RxJava Before Reacting
How to Think in RxJava Before Reacting
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
 
rx.js make async programming simpler
rx.js make async programming simplerrx.js make async programming simpler
rx.js make async programming simpler
 
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
 
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
 

More from Aaron Douglas

More from Aaron Douglas (6)

Leadership in Fully Remote Teams
Leadership in Fully Remote TeamsLeadership in Fully Remote Teams
Leadership in Fully Remote Teams
 
Working from Wherever
Working from WhereverWorking from Wherever
Working from Wherever
 
WordPress for iOS - Under the Hood
WordPress for iOS - Under the HoodWordPress for iOS - Under the Hood
WordPress for iOS - Under the Hood
 
WordPress Mobile Apps - WordCamp San Antonio 2015
WordPress Mobile Apps - WordCamp San Antonio 2015WordPress Mobile Apps - WordCamp San Antonio 2015
WordPress Mobile Apps - WordCamp San Antonio 2015
 
Advanced Core Data - The Things You Thought You Could Ignore
Advanced Core Data - The Things You Thought You Could IgnoreAdvanced Core Data - The Things You Thought You Could Ignore
Advanced Core Data - The Things You Thought You Could Ignore
 
Localization Realization
Localization RealizationLocalization Realization
Localization Realization
 

Recently uploaded

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 

Recently uploaded (20)

08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 

Swift & ReactiveX – Asynchronous Event-Based Funsies with RxSwift