Introduction to Functional Reactive Programming

About me
Eliasz Sawicki
Blog: www.eliaszsawicki.com
Twitter: @EliSawic
@EliSawic
Introduction to
Functional Reactive
Programming
@EliSawic
Agenda
• What is Functional Reactive Programming?
• Let's take a look at ReactiveCocoa
• Working with streams
• Real life example
• Conclusion
@EliSawic
Functional Reactive
Programming
@EliSawic
Wikipedia
Functional reactive programming (FRP) is a programming
paradigm for reactive programming (asynchronous dataflow
programming) using the building blocks of functional
programming (e.g. map, reduce, filter).
@EliSawic
Reactive
Programming
@EliSawic
Asynchronous
Dataflow
@EliSawic
Reacting to state
changes
@EliSawic
Functional
Programming
@EliSawic
Immutable
@EliSawic
assert(f(x) == f(x))
@EliSawic
A person
class Person {
let name: String
let phoneNumber: String
init(name: String, phoneNumber: String) {
self.name = name
self.phoneNumber = phoneNumber
}
}
class MobilePhone {
func call(person: Person) -> Bool {
// implementation
}
}
@EliSawic
Mutable
let mobilePhone = MobilePhone()
let john = Person(name: "John", phoneNumber: "123456789")
func makeAPhoneCall(device: Phone, person: Person, countryCode: String) -> Bool {
person.phoneNumber = countryCode + person.phoneNumber
let success = device.call(person)
return success
}
makeAPhoneCall(device: mobilePhone, person: john, countryCode: "+48") // true
makeAPhoneCall(device: mobilePhone, person: john, countryCode: "+48") // false
makeAPhoneCall(device: mobilePhone, person: john, countryCode: "+48") // false
@EliSawic
Immutable
let mobilePhone = MobilePhone()
let john = Person(name: "John", phoneNumber: "123456789")
func makeAPhoneCall(device: Phone, person: Person, countryCode: String) -> Bool {
let prefixedPhoneNumber = countryCode + person.phoneNumber
let newPerson = Person(name: person.name, phoneNumber: prefixedPhoneNumber)
let success = device.call(newPerson)
return success
}
makeAPhoneCall(device: mobilePhone, person: john, countryCode: "+48") // true
makeAPhoneCall(device: mobilePhone, person: john, countryCode: "+48") // true
makeAPhoneCall(device: mobilePhone, person: john, countryCode: "+48") // true
@EliSawic
Stateless
@EliSawic
Stateful
var value = 0
func increment() -> Int {
value += 1
return value
}
@EliSawic
Stateless
func increment(value: Int) -> Int {
return value + 1
}
@EliSawic
Functional Reactive
Programming
@EliSawic
Imperative
vs
Declarative
@EliSawic
Imperative
@EliSawic
Imperative
let array = [0, 1, 2, 3, 4, 5]
var evenNumbers = [Int]()
for element in array {
if element % 2 == 0 {
evenNumbers.append(element)
}
}
@EliSawic
Declarative
@EliSawic
Declarative
let array = [0, 1, 2, 3, 4, 5]
let evenNumbers = array.filter { $0 % 2 == 0 }
@EliSawic
ReactiveCocoa
@EliSawic
Event streams
@EliSawic
Event Stream
@EliSawic
Event
@EliSawic
Non-Terminating
• Next
@EliSawic
Terminating
• Completed
• Failed
• Interrupted (Reactive Cocoa)
@EliSawic
Signal
@EliSawic
Events over time
@EliSawic
No side effects
@EliSawic
No random access to
events
@EliSawic
Must be observed in
order to access it's
events
@EliSawic
Hot
@EliSawic
Signal's lifetime
• Passes any number of Next events
• "Dies" when terminating event
• Any new observer will receive Interrupted event
@EliSawic
Observing
let someWork = Signal<Int, NoError> { observer in
observer.sendNext(1)
observer.sendNext(2)
....
observer.sendNext(1000000)
observer.sendCompleted()
}
signal.observe { (event) in
print(event)
}
signal.observeNext { (value) in
print(value)
}
signal.observeCompleted {
print("Completed")
}
@EliSawic
Pipe
@EliSawic
Pipe
let (signal, observer) = Signal<String, NoError>.pipe()
signal.observeNext({ text in
print(text)
})
signal.observeCompleted({
print("Test completed")
})
observer.sendNext("It's a test") // It's a test
observer.sendCompleted() // Test completed
@EliSawic
SignalProducer
@EliSawic
Represents tasks
@EliSawic
Creates signal
@EliSawic
Possible side effects
@EliSawic
Does not start it's
work if not started
@EliSawic
Cold
@EliSawic
Using Signal Producer
let producer = SignalProducer<String, NSError> { (observer, composite) in
observer.sendNext("In Progress...")
// ......
observer.sendCompleted()
}
producer.startWithSignal { (signal, _) in
signal.observeNext({ (text) in
print(text) // In Progress...
})
signal.observeCompleted({
print("Test completed") // Test completed
})
}
@EliSawic
Cold vs Hot
@EliSawic
Properties
@EliSawic
MutableProperty
let name = MutableProperty("Bob")
name.producer.startWithNext { (text) in
print(text)
}
name.value = "Lisa"
@EliSawic
Bindings
@EliSawic
Basic binding
let property = MutableProperty<String>("")
let (signal, _) = Signal<String, NoError>.pipe()
property <~ signal
@EliSawic
Schedulers
@EliSawic
Memory Management
@EliSawic
Disposables
@EliSawic
Manipulating signals
@EliSawic
Map
@EliSawic
Filter
@EliSawic
Aggregating
@EliSawic
Skip repeats
@EliSawic
Manipulating
multiple signals
@EliSawic
Combine latest
@EliSawic
Zip
@EliSawic
Merge
@EliSawic
Chaining operators
@EliSawic
Chain them all!
let newSignalX = signalX.skipRepeats()
.filter { x > 2 }
.map { x * 10 }
let newSignalY = signalY.filter { x > 10 }
let combined = combineLatest(newSignalX, newSignalY)
combined.observeNext { xValue, yValue in
print("Update: (xValue) : (yValue)")
}
@EliSawic
Example
@EliSawic
@EliSawic
@EliSawic
@EliSawic
@EliSawic
@EliSawic
How does it work?
@EliSawic
Is name valid?
let isValidName = nameSignal.map { (name) -> Bool in
return input.characters.count > 2
}
@EliSawic
Is mail valid?
let isValidMail = mailSignal.map { (mail) -> Bool in
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,}"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailTest.evaluateWithObject(mail)
}
@EliSawic
Combine Latest
let formData = combineLatest(isValidName,
isValidSurname,
isValidMail)
@EliSawic
Is form valid?
disposables += isFormValid <~ formData.map {
(isValidName, isValidSurname, isValidMail) -> Bool in
return isValidMail && isValidSurname && isValidMail
}
@EliSawic
Button state
let producer = isFormValid.producer.skipRepeats()
disposables += producer.startWithNext {[unowned self] (isValid) in
self.updateAcceptButtonWithState(isValid)
}
@EliSawic
Conclusion
@EliSawic
Thank you for your
attention!
@EliSawic
1 of 79

Recommended

Introduction To Functional Reactive Programming Poznan by
Introduction To Functional Reactive Programming PoznanIntroduction To Functional Reactive Programming Poznan
Introduction To Functional Reactive Programming PoznanEliasz Sawicki
802 views82 slides
Code europe by
Code europeCode europe
Code europeEliasz Sawicki
549 views71 slides
Make your programs Free by
Make your programs FreeMake your programs Free
Make your programs FreePawel Szulc
3.9K views149 slides
Functional Reactive Programming by
Functional Reactive ProgrammingFunctional Reactive Programming
Functional Reactive ProgrammingAlessandro Melchiori
791 views52 slides
Tech fest by
Tech festTech fest
Tech festEliasz Sawicki
289 views143 slides
iOSCon by
iOSConiOSCon
iOSConEliasz Sawicki
455 views36 slides

More Related Content

Similar to Introduction to Functional Reactive Programming

The Evolution of Async-Programming (SD 2.0, JavaScript) by
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
2K views64 slides
The Evolution of Async-Programming on .NET Platform (.Net China, C#) by
The Evolution of Async-Programming on .NET Platform (.Net China, C#)The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)jeffz
2.1K views61 slides
Introduction to Reactive Extensions without saying functional reactive by
Introduction to Reactive Extensions without saying functional reactiveIntroduction to Reactive Extensions without saying functional reactive
Introduction to Reactive Extensions without saying functional reactiveTetsuharu OHZEKI
611 views34 slides
Functional Reactive Endpoints using Spring 5 by
Functional Reactive Endpoints using Spring 5Functional Reactive Endpoints using Spring 5
Functional Reactive Endpoints using Spring 5Rory Preddy
280 views19 slides
Reactive Streams, j.u.concurrent, & Beyond! by
Reactive Streams, j.u.concurrent, & Beyond!Reactive Streams, j.u.concurrent, & Beyond!
Reactive Streams, j.u.concurrent, & Beyond!C4Media
576 views143 slides
Coscup by
CoscupCoscup
Coscup宇宣 賴
822 views78 slides

Similar to Introduction to Functional Reactive Programming(20)

The Evolution of Async-Programming (SD 2.0, JavaScript) by jeffz
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)
jeffz2K views
The Evolution of Async-Programming on .NET Platform (.Net China, C#) by jeffz
The Evolution of Async-Programming on .NET Platform (.Net China, C#)The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
jeffz2.1K views
Introduction to Reactive Extensions without saying functional reactive by Tetsuharu OHZEKI
Introduction to Reactive Extensions without saying functional reactiveIntroduction to Reactive Extensions without saying functional reactive
Introduction to Reactive Extensions without saying functional reactive
Tetsuharu OHZEKI611 views
Functional Reactive Endpoints using Spring 5 by Rory Preddy
Functional Reactive Endpoints using Spring 5Functional Reactive Endpoints using Spring 5
Functional Reactive Endpoints using Spring 5
Rory Preddy280 views
Reactive Streams, j.u.concurrent, & Beyond! by C4Media
Reactive Streams, j.u.concurrent, & Beyond!Reactive Streams, j.u.concurrent, & Beyond!
Reactive Streams, j.u.concurrent, & Beyond!
C4Media576 views
Building Self-Defending Applications With OWASP AppSensor JavaOne 2016 by jtmelton
Building Self-Defending Applications With OWASP AppSensor JavaOne 2016Building Self-Defending Applications With OWASP AppSensor JavaOne 2016
Building Self-Defending Applications With OWASP AppSensor JavaOne 2016
jtmelton2.6K views
Intro to ReactiveCocoa by kleneau
Intro to ReactiveCocoaIntro to ReactiveCocoa
Intro to ReactiveCocoa
kleneau1.1K views
AppSensor CodeMash 2017 by jtmelton
AppSensor CodeMash 2017AppSensor CodeMash 2017
AppSensor CodeMash 2017
jtmelton560 views
Reactive Extensions .NET by George Taskos
Reactive Extensions .NETReactive Extensions .NET
Reactive Extensions .NET
George Taskos674 views
Alexey Golub - Dependency absolution (application as a pipeline) | Svitla Sma... by Oleksii Holub
Alexey Golub - Dependency absolution (application as a pipeline) | Svitla Sma...Alexey Golub - Dependency absolution (application as a pipeline) | Svitla Sma...
Alexey Golub - Dependency absolution (application as a pipeline) | Svitla Sma...
Oleksii Holub172 views
The Need for Async @ ScalaWorld by Konrad Malawski
The Need for Async @ ScalaWorldThe Need for Async @ ScalaWorld
The Need for Async @ ScalaWorld
Konrad Malawski4.5K views
End to End Akka Streams / Reactive Streams - from Business to Socket by Konrad Malawski
End to End Akka Streams / Reactive Streams - from Business to SocketEnd to End Akka Streams / Reactive Streams - from Business to Socket
End to End Akka Streams / Reactive Streams - from Business to Socket
Konrad Malawski1.8K views
Need for Async: Hot pursuit for scalable applications by Konrad Malawski
Need for Async: Hot pursuit for scalable applicationsNeed for Async: Hot pursuit for scalable applications
Need for Async: Hot pursuit for scalable applications
Konrad Malawski6.2K views

More from Eliasz Sawicki

Redux - 4Developers by
Redux - 4DevelopersRedux - 4Developers
Redux - 4DevelopersEliasz Sawicki
130 views110 slides
Eliasz sawickimeetupit by
Eliasz sawickimeetupitEliasz sawickimeetupit
Eliasz sawickimeetupitEliasz Sawicki
110 views20 slides
Developing more in less time by
Developing more in less timeDeveloping more in less time
Developing more in less timeEliasz Sawicki
138 views121 slides
The art-of-developing-more-in-less-time-berlin by
The art-of-developing-more-in-less-time-berlinThe art-of-developing-more-in-less-time-berlin
The art-of-developing-more-in-less-time-berlinEliasz Sawicki
273 views111 slides
Introduction to react native by
Introduction to react nativeIntroduction to react native
Introduction to react nativeEliasz Sawicki
481 views78 slides
Doing more in less time - Mobiconf by
Doing more in less time - MobiconfDoing more in less time - Mobiconf
Doing more in less time - MobiconfEliasz Sawicki
390 views107 slides

More from Eliasz Sawicki(10)

Introduction to Functional Reactive Programming