SlideShare une entreprise Scribd logo
1  sur  24
Télécharger pour lire hors ligne
KVO with ReactiveCocoa
An easy way to start with RAC
CocoaHeads Paris

Jeudi 09 septembre 2015
Philippe Converset
Introduction
ReactiveCocoa helps solving asynchronous
problems
But some concepts are hard to grasp
And many methods are available
How to start with RAC?
Use ReactiveCocoa has a KVO alternative
Learn little by little its features and concepts
RAC KVO Code
NSString *const kCurrentUserKey = @“currentUser";



[self removeObserver:self forKeyPath:kCurrentUserKey context:&kMyContext];

… 

[self addObserver:self forKeyPath:kCurrentUserKey options:NSKeyValueObservingOptionNew context:&kMyContext]
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void
*)context

{

if([keyPath isEqualToString:kCurrentUserKey])

{

…

}

}
- (void)setCurrentUser:(User *)user

{

if(_currentUser != user)

{

[self willChangeValueForKey:kCurrentUserKey];

_currentUser = user;

[self didChangeValueForKey:kCurrentUserKey];

}

}
RAC(self, userNameLabel) = [RACObserve(self, userManager.currentUser.name) deliverOnMainThread];
Basic usages
Simple binding
Typical binding
RAC(self, userName) = RACObserve(self, userManager.currentUser.lastName);
userName is bound to userManager.currentUser.lastName.
But what if userManager or currentUser is nil?
RAC(self, userName, @“none”) = RACObserve(self, userManager.currentUser.lastName);
Bonus: Don’t care whether objects in observed
keypath are already allocated
Observing changes only
distinctUntilChanged
RAC(self, userName) = [RACObserve(self,
userManager.currentUser.lastName) distinctUntilChanged];
Transforming
map:
RAC(self, userName) = [RACObserve(self, userManager.currentUser)
map:^id(User *user) {

return user.lastName;

}];
RAC(self, userName) = [RACObserve(self, userManager.currentUser)
map:^id(User *user) {

return (user == nil ? nil : [NSString stringWithFormat:@"%@ %@",
user.firstName, user.lastName]);

}];
Calling some code
subscribeNext:
[RACObserve(self, userManager.currentUser) subscribeNext:^(User *user) {

if(user)

{

NSLog(@"%@", user.lastName);

}

}];
Filtering
filter:
[[RACObserve(self, userManager.currentUser) filter:^BOOL(User *user) {

return (user != nil) && user.admin;

}] subscribeNext:^(User *user) {

NSLog(@"%@ is admin", user.lastName);

}];
Specifying thread
deliverOnMainThread
RAC(self, userNameLabel.text) = [RACObserve(self,
modelView.userName) deliverOnMainThread];
deliverOn:
[[RACObserve(self, modelView.userName) deliverOn:self.scheduler]
subscribeNext:^(User *user) {

NSLog(@"I'm executed in a specific dispatch queue");

}];
Notification
rac_addObserverForName:
RAC(self, loggedIn) = [NSNotificationCenter.defaultCenter 

rac_addObserverForName:kUserDidLogOutNotification object:nil]

mapReplace:@NO];
Combining
combineLatest & reduce
RAC(self, createEnabled) = [RACSignal

combineLatest:@[RACObserve(self, password), RACObserve(self, passwordConfirmation)]

reduce:^(NSString *password, NSString *passwordConfirm) {

return @([passwordConfirm isEqualToString:password]);

}];
Generalities
Parameters as id
Most RAC methods return RACSignal and use
id as parameters
[RACObserve(self, userManager.currentUser) subscribeNext:^(id x) {

NSLog(@"%@", ((User *)x).lastName);

}];
☟
[RACObserve(self, userManager.currentUser) subscribeNext:^(User *user) {

NSLog(@"%@", user.lastName);

}];
Weakify/Strongify
@weakify(self)

[RACObserve(self, userManager.currentUser) subscribeNext:^(User *user) {

@strongify(self)

[self userChanged:user];

}];
@weakify creates a new weakly referenced variable of the same type you
pass in and assigns the original value to it
@strongify creates a variable that matches the original variable but it exists
in the local scope and assigns to it the variable created by @weakify
Weakify/Strongify
_weak id weakSelf = self;

[RACObserve(self, userManager.currentUser) subscribeNext:^(User *user) {

id strongSelf = weakSelf;

[strongSelf userChanged:user];

}];
@strongify in each async block
No need for several @weakify(self)
Pros and Cons
Pros
Get rid of boilerplate code
Less error prone

(missing automaticallyNotifiesObserversOf<Property>?)
Compatible with property refactoring (no more
reference to keypath as string)

If you change a property name manually, RAC code won’t compile
anymore.
Configuration is much easier, especially with multilevel
keypath
Memory management is rightly done out of the box
Start to think functional, prepare for Swift
Cons
All values are object, BOOL are passed as
NSNumber

=> isAdmin.boolValue 😢
Don’t forget deliverOnMainThread for UIKit
components
Warnings
Don’t use RAC on intensive property change

for example on Player.currentTime
Don’t look at the stack!











Warnings
Don’t use RAC on intensive property change

for example on Player.currentTime
Don’t look at the stack!











CocoaHeads Paris

KVO with ReactiveCocoa
Philippe Converset
pconverset@autresphere.com
@autresphere
www.autresphere.com
www.kidzik.com
github.com/autresphere

Contenu connexe

Tendances

Node Boot Camp
Node Boot CampNode Boot Camp
Node Boot CampTroy Miles
 
Taking Objective-C to the next level. UA Mobile 2016.
Taking Objective-C to the next level. UA Mobile 2016.Taking Objective-C to the next level. UA Mobile 2016.
Taking Objective-C to the next level. UA Mobile 2016.UA Mobile
 
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
 
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...andreaslubbe
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jscacois
 
Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptVisual Engineering
 
第4回 g* ワークショップ はじめてみよう! Grailsプラグイン
第4回 g* ワークショップ はじめてみよう! Grailsプラグイン第4回 g* ワークショップ はじめてみよう! Grailsプラグイン
第4回 g* ワークショップ はじめてみよう! GrailsプラグインTsuyoshi Yamamoto
 
Js interpreter interpreted
Js interpreter interpretedJs interpreter interpreted
Js interpreter interpretedMartha Schumann
 
ReactiveCocoa Goodness - Part I of II
ReactiveCocoa Goodness - Part I of IIReactiveCocoa Goodness - Part I of II
ReactiveCocoa Goodness - Part I of IImanuelmaly
 
Reactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwiftReactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwiftFlorent Pillet
 
Reactive, component 그리고 angular2
Reactive, component 그리고  angular2Reactive, component 그리고  angular2
Reactive, component 그리고 angular2Jeado Ko
 
ECMAScript 6 and the Node Driver
ECMAScript 6 and the Node DriverECMAScript 6 and the Node Driver
ECMAScript 6 and the Node DriverMongoDB
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Tsuyoshi Yamamoto
 
Introduction to asynchronous DB access using Node.js and MongoDB
Introduction to asynchronous DB access using Node.js and MongoDBIntroduction to asynchronous DB access using Node.js and MongoDB
Introduction to asynchronous DB access using Node.js and MongoDBAdrien Joly
 
The Promised Land (in Angular)
The Promised Land (in Angular)The Promised Land (in Angular)
The Promised Land (in Angular)Domenic Denicola
 
An Introduction to Reactive Cocoa
An Introduction to Reactive CocoaAn Introduction to Reactive Cocoa
An Introduction to Reactive CocoaSmartLogic
 

Tendances (20)

Node Boot Camp
Node Boot CampNode Boot Camp
Node Boot Camp
 
Taking Objective-C to the next level. UA Mobile 2016.
Taking Objective-C to the next level. UA Mobile 2016.Taking Objective-C to the next level. UA Mobile 2016.
Taking Objective-C to the next level. UA Mobile 2016.
 
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
 
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
 
OneRing @ OSCamp 2010
OneRing @ OSCamp 2010OneRing @ OSCamp 2010
OneRing @ OSCamp 2010
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
 
Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScript
 
Présentation de HomeKit
Présentation de HomeKitPrésentation de HomeKit
Présentation de HomeKit
 
第4回 g* ワークショップ はじめてみよう! Grailsプラグイン
第4回 g* ワークショップ はじめてみよう! Grailsプラグイン第4回 g* ワークショップ はじめてみよう! Grailsプラグイン
第4回 g* ワークショップ はじめてみよう! Grailsプラグイン
 
Js interpreter interpreted
Js interpreter interpretedJs interpreter interpreted
Js interpreter interpreted
 
ReactiveCocoa Goodness - Part I of II
ReactiveCocoa Goodness - Part I of IIReactiveCocoa Goodness - Part I of II
ReactiveCocoa Goodness - Part I of II
 
Reactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwiftReactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwift
 
Reactive, component 그리고 angular2
Reactive, component 그리고  angular2Reactive, component 그리고  angular2
Reactive, component 그리고 angular2
 
ECMAScript 6 and the Node Driver
ECMAScript 6 and the Node DriverECMAScript 6 and the Node Driver
ECMAScript 6 and the Node Driver
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
 
Introduction to asynchronous DB access using Node.js and MongoDB
Introduction to asynchronous DB access using Node.js and MongoDBIntroduction to asynchronous DB access using Node.js and MongoDB
Introduction to asynchronous DB access using Node.js and MongoDB
 
The Promised Land (in Angular)
The Promised Land (in Angular)The Promised Land (in Angular)
The Promised Land (in Angular)
 
An Introduction to Reactive Cocoa
An Introduction to Reactive CocoaAn Introduction to Reactive Cocoa
An Introduction to Reactive Cocoa
 
Promises, Promises
Promises, PromisesPromises, Promises
Promises, Promises
 
JavaScript Promise
JavaScript PromiseJavaScript Promise
JavaScript Promise
 

En vedette

Collection pipeline par Mathieu Godart
Collection pipeline par  Mathieu GodartCollection pipeline par  Mathieu Godart
Collection pipeline par Mathieu GodartCocoaHeads France
 
Code flow - Cocoaheads paris
Code flow - Cocoaheads parisCode flow - Cocoaheads paris
Code flow - Cocoaheads parisCocoaHeads France
 
NSLogger network logging extension
NSLogger network logging extensionNSLogger network logging extension
NSLogger network logging extensionCocoaHeads France
 
App Transport Security by Nicolas lauquin
App Transport Security by Nicolas lauquinApp Transport Security by Nicolas lauquin
App Transport Security by Nicolas lauquinCocoaHeads France
 
How javascript core helped PAW to move from a small app to an extensible tool
How javascript core helped PAW to move from a small app to an extensible toolHow javascript core helped PAW to move from a small app to an extensible tool
How javascript core helped PAW to move from a small app to an extensible toolCocoaHeads France
 
BlaBlaCar et la mise en place d'une fonctionnalité FlagFeature
BlaBlaCar et la mise en place d'une fonctionnalité FlagFeatureBlaBlaCar et la mise en place d'une fonctionnalité FlagFeature
BlaBlaCar et la mise en place d'une fonctionnalité FlagFeatureCocoaHeads France
 
Genius scan - Du boostrap à 20 millions d’utilisateurs, techniques et outils ...
Genius scan - Du boostrap à 20 millions d’utilisateurs, techniques et outils ...Genius scan - Du boostrap à 20 millions d’utilisateurs, techniques et outils ...
Genius scan - Du boostrap à 20 millions d’utilisateurs, techniques et outils ...CocoaHeads France
 

En vedette (20)

Mach-O par Stéphane Sudre
Mach-O par Stéphane SudreMach-O par Stéphane Sudre
Mach-O par Stéphane Sudre
 
Couverture de code
Couverture de codeCouverture de code
Couverture de code
 
Revue des annonces WWDC2015
Revue des annonces WWDC2015Revue des annonces WWDC2015
Revue des annonces WWDC2015
 
Collection pipeline par Mathieu Godart
Collection pipeline par  Mathieu GodartCollection pipeline par  Mathieu Godart
Collection pipeline par Mathieu Godart
 
Code flow - Cocoaheads paris
Code flow - Cocoaheads parisCode flow - Cocoaheads paris
Code flow - Cocoaheads paris
 
Mastering Interface Builder
Mastering Interface BuilderMastering Interface Builder
Mastering Interface Builder
 
NSLogger network logging extension
NSLogger network logging extensionNSLogger network logging extension
NSLogger network logging extension
 
App Transport Security by Nicolas lauquin
App Transport Security by Nicolas lauquinApp Transport Security by Nicolas lauquin
App Transport Security by Nicolas lauquin
 
How javascript core helped PAW to move from a small app to an extensible tool
How javascript core helped PAW to move from a small app to an extensible toolHow javascript core helped PAW to move from a small app to an extensible tool
How javascript core helped PAW to move from a small app to an extensible tool
 
Conférence DotSwift 2016
Conférence DotSwift 2016Conférence DotSwift 2016
Conférence DotSwift 2016
 
POI clusturing
POI clusturingPOI clusturing
POI clusturing
 
App-resizer Library
App-resizer LibraryApp-resizer Library
App-resizer Library
 
BlaBlaCar et la mise en place d'une fonctionnalité FlagFeature
BlaBlaCar et la mise en place d'une fonctionnalité FlagFeatureBlaBlaCar et la mise en place d'une fonctionnalité FlagFeature
BlaBlaCar et la mise en place d'une fonctionnalité FlagFeature
 
3D Touch
3D Touch3D Touch
3D Touch
 
Genius scan - Du boostrap à 20 millions d’utilisateurs, techniques et outils ...
Genius scan - Du boostrap à 20 millions d’utilisateurs, techniques et outils ...Genius scan - Du boostrap à 20 millions d’utilisateurs, techniques et outils ...
Genius scan - Du boostrap à 20 millions d’utilisateurs, techniques et outils ...
 
Découverte de HomeKit
Découverte de HomeKitDécouverte de HomeKit
Découverte de HomeKit
 
Swift open source
Swift open sourceSwift open source
Swift open source
 
Project Entourage
Project EntourageProject Entourage
Project Entourage
 
Apple Search Optimization
Apple Search OptimizationApple Search Optimization
Apple Search Optimization
 
What's new in iOS9
What's new in iOS9What's new in iOS9
What's new in iOS9
 

Similaire à Talk KVO with rac by Philippe Converset

High Performance Core Data
High Performance Core DataHigh Performance Core Data
High Performance Core DataMatthew Morey
 
Intro to ReactiveCocoa
Intro to ReactiveCocoaIntro to ReactiveCocoa
Intro to ReactiveCocoakleneau
 
Learn You a ReactiveCocoa for Great Good
Learn You a ReactiveCocoa for Great GoodLearn You a ReactiveCocoa for Great Good
Learn You a ReactiveCocoa for Great GoodJason Larsen
 
Functional Reactive Programming (CocoaHeads Bratislava)
Functional Reactive Programming (CocoaHeads Bratislava)Functional Reactive Programming (CocoaHeads Bratislava)
Functional Reactive Programming (CocoaHeads Bratislava)Michal Grman
 
Jasigsakai12 columbia-customizes-cas
Jasigsakai12 columbia-customizes-casJasigsakai12 columbia-customizes-cas
Jasigsakai12 columbia-customizes-casellentuck
 
«ReactiveCocoa и MVVM» — Николай Касьянов, SoftWear
«ReactiveCocoa и MVVM» — Николай Касьянов, SoftWear«ReactiveCocoa и MVVM» — Николай Касьянов, SoftWear
«ReactiveCocoa и MVVM» — Николай Касьянов, SoftWeare-Legion
 
How to perform debounce in react
How to perform debounce in reactHow to perform debounce in react
How to perform debounce in reactBOSC Tech Labs
 
Reactive cocoa
Reactive cocoaReactive cocoa
Reactive cocoaiacisclo
 
Universal JS Applications with React
Universal JS Applications with ReactUniversal JS Applications with React
Universal JS Applications with ReactThanh Trần Trọng
 
Lviv MD Day 2015 Павло Захаров "Reactive cocoa: paradigm shift"
Lviv MD Day 2015 Павло Захаров "Reactive cocoa: paradigm shift"Lviv MD Day 2015 Павло Захаров "Reactive cocoa: paradigm shift"
Lviv MD Day 2015 Павло Захаров "Reactive cocoa: paradigm shift"Lviv Startup Club
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasminePaulo Ragonha
 
Property Wrappers or how Swift decided to become Java
Property Wrappers or how Swift decided to become JavaProperty Wrappers or how Swift decided to become Java
Property Wrappers or how Swift decided to become JavaVincent Pradeilles
 
Custom gutenberg block development in react
Custom gutenberg block development in reactCustom gutenberg block development in react
Custom gutenberg block development in reactImran Sayed
 
MBL301 Data Persistence to Amazon Dynamodb for Mobile Apps - AWS re: Invent 2012
MBL301 Data Persistence to Amazon Dynamodb for Mobile Apps - AWS re: Invent 2012MBL301 Data Persistence to Amazon Dynamodb for Mobile Apps - AWS re: Invent 2012
MBL301 Data Persistence to Amazon Dynamodb for Mobile Apps - AWS re: Invent 2012Amazon Web Services
 
RESTfull with RestKit
RESTfull with RestKitRESTfull with RestKit
RESTfull with RestKitTaras Kalapun
 

Similaire à Talk KVO with rac by Philippe Converset (20)

High Performance Core Data
High Performance Core DataHigh Performance Core Data
High Performance Core Data
 
Intro to ReactiveCocoa
Intro to ReactiveCocoaIntro to ReactiveCocoa
Intro to ReactiveCocoa
 
Learn You a ReactiveCocoa for Great Good
Learn You a ReactiveCocoa for Great GoodLearn You a ReactiveCocoa for Great Good
Learn You a ReactiveCocoa for Great Good
 
Intro to Laravel 4
Intro to Laravel 4Intro to Laravel 4
Intro to Laravel 4
 
Functional Reactive Programming (CocoaHeads Bratislava)
Functional Reactive Programming (CocoaHeads Bratislava)Functional Reactive Programming (CocoaHeads Bratislava)
Functional Reactive Programming (CocoaHeads Bratislava)
 
Jasigsakai12 columbia-customizes-cas
Jasigsakai12 columbia-customizes-casJasigsakai12 columbia-customizes-cas
Jasigsakai12 columbia-customizes-cas
 
«ReactiveCocoa и MVVM» — Николай Касьянов, SoftWear
«ReactiveCocoa и MVVM» — Николай Касьянов, SoftWear«ReactiveCocoa и MVVM» — Николай Касьянов, SoftWear
«ReactiveCocoa и MVVM» — Николай Касьянов, SoftWear
 
How to perform debounce in react
How to perform debounce in reactHow to perform debounce in react
How to perform debounce in react
 
Reactive cocoa
Reactive cocoaReactive cocoa
Reactive cocoa
 
Universal JS Applications with React
Universal JS Applications with ReactUniversal JS Applications with React
Universal JS Applications with React
 
XQuery Rocks
XQuery RocksXQuery Rocks
XQuery Rocks
 
Reduxing like a pro
Reduxing like a proReduxing like a pro
Reduxing like a pro
 
Not your Grandma's XQuery
Not your Grandma's XQueryNot your Grandma's XQuery
Not your Grandma's XQuery
 
Lviv MD Day 2015 Павло Захаров "Reactive cocoa: paradigm shift"
Lviv MD Day 2015 Павло Захаров "Reactive cocoa: paradigm shift"Lviv MD Day 2015 Павло Захаров "Reactive cocoa: paradigm shift"
Lviv MD Day 2015 Павло Захаров "Reactive cocoa: paradigm shift"
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
 
Property Wrappers or how Swift decided to become Java
Property Wrappers or how Swift decided to become JavaProperty Wrappers or how Swift decided to become Java
Property Wrappers or how Swift decided to become Java
 
Custom gutenberg block development in react
Custom gutenberg block development in reactCustom gutenberg block development in react
Custom gutenberg block development in react
 
MBL301 Data Persistence to Amazon Dynamodb for Mobile Apps - AWS re: Invent 2012
MBL301 Data Persistence to Amazon Dynamodb for Mobile Apps - AWS re: Invent 2012MBL301 Data Persistence to Amazon Dynamodb for Mobile Apps - AWS re: Invent 2012
MBL301 Data Persistence to Amazon Dynamodb for Mobile Apps - AWS re: Invent 2012
 
Reactive cocoa
Reactive cocoaReactive cocoa
Reactive cocoa
 
RESTfull with RestKit
RESTfull with RestKitRESTfull with RestKit
RESTfull with RestKit
 

Plus de CocoaHeads France

Mutation testing for a safer Future
Mutation testing for a safer FutureMutation testing for a safer Future
Mutation testing for a safer FutureCocoaHeads France
 
Visual accessibility in iOS11
Visual accessibility in iOS11Visual accessibility in iOS11
Visual accessibility in iOS11CocoaHeads France
 
My script - One year of CocoaHeads
My script - One year of CocoaHeadsMy script - One year of CocoaHeads
My script - One year of CocoaHeadsCocoaHeads France
 
Ui testing dealing with push notifications
Ui testing dealing with push notificationsUi testing dealing with push notifications
Ui testing dealing with push notificationsCocoaHeads France
 
CONTINUOUS DELIVERY WITH FASTLANE
CONTINUOUS DELIVERY WITH FASTLANECONTINUOUS DELIVERY WITH FASTLANE
CONTINUOUS DELIVERY WITH FASTLANECocoaHeads France
 
L'intégration continue avec Bitrise
L'intégration continue avec BitriseL'intégration continue avec Bitrise
L'intégration continue avec BitriseCocoaHeads France
 
Programme MFI retour d'expérience
Programme MFI retour d'expérienceProgramme MFI retour d'expérience
Programme MFI retour d'expérienceCocoaHeads France
 
How to communicate with Smart things?
How to communicate with Smart things?How to communicate with Smart things?
How to communicate with Smart things?CocoaHeads France
 
Build a lego app with CocoaPods
Build a lego app with CocoaPodsBuild a lego app with CocoaPods
Build a lego app with CocoaPodsCocoaHeads France
 
Comment faire de HLS votre solution vidéo préférée ?
Comment faire de HLS votre solution vidéo préférée ?Comment faire de HLS votre solution vidéo préférée ?
Comment faire de HLS votre solution vidéo préférée ?CocoaHeads France
 

Plus de CocoaHeads France (20)

Mutation testing for a safer Future
Mutation testing for a safer FutureMutation testing for a safer Future
Mutation testing for a safer Future
 
iOS App Group for Debugging
iOS App Group for DebuggingiOS App Group for Debugging
iOS App Group for Debugging
 
Asynchronous swift
Asynchronous swiftAsynchronous swift
Asynchronous swift
 
Visual accessibility in iOS11
Visual accessibility in iOS11Visual accessibility in iOS11
Visual accessibility in iOS11
 
My script - One year of CocoaHeads
My script - One year of CocoaHeadsMy script - One year of CocoaHeads
My script - One year of CocoaHeads
 
Ui testing dealing with push notifications
Ui testing dealing with push notificationsUi testing dealing with push notifications
Ui testing dealing with push notifications
 
CONTINUOUS DELIVERY WITH FASTLANE
CONTINUOUS DELIVERY WITH FASTLANECONTINUOUS DELIVERY WITH FASTLANE
CONTINUOUS DELIVERY WITH FASTLANE
 
L'intégration continue avec Bitrise
L'intégration continue avec BitriseL'intégration continue avec Bitrise
L'intégration continue avec Bitrise
 
Super combinators
Super combinatorsSuper combinators
Super combinators
 
Design like a developer
Design like a developerDesign like a developer
Design like a developer
 
Handle the error
Handle the errorHandle the error
Handle the error
 
Quoi de neuf dans iOS 10.3
Quoi de neuf dans iOS 10.3Quoi de neuf dans iOS 10.3
Quoi de neuf dans iOS 10.3
 
SwiftyGPIO
SwiftyGPIOSwiftyGPIO
SwiftyGPIO
 
Programme MFI retour d'expérience
Programme MFI retour d'expérienceProgramme MFI retour d'expérience
Programme MFI retour d'expérience
 
How to communicate with Smart things?
How to communicate with Smart things?How to communicate with Smart things?
How to communicate with Smart things?
 
Build a lego app with CocoaPods
Build a lego app with CocoaPodsBuild a lego app with CocoaPods
Build a lego app with CocoaPods
 
Let's migrate to Swift 3.0
Let's migrate to Swift 3.0Let's migrate to Swift 3.0
Let's migrate to Swift 3.0
 
BitTorrent on iOS
BitTorrent on iOSBitTorrent on iOS
BitTorrent on iOS
 
CloudKit as a backend
CloudKit as a backendCloudKit as a backend
CloudKit as a backend
 
Comment faire de HLS votre solution vidéo préférée ?
Comment faire de HLS votre solution vidéo préférée ?Comment faire de HLS votre solution vidéo préférée ?
Comment faire de HLS votre solution vidéo préférée ?
 

Dernier

SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 

Dernier (20)

SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 

Talk KVO with rac by Philippe Converset

  • 1. KVO with ReactiveCocoa An easy way to start with RAC CocoaHeads Paris
 Jeudi 09 septembre 2015 Philippe Converset
  • 2. Introduction ReactiveCocoa helps solving asynchronous problems But some concepts are hard to grasp And many methods are available
  • 3. How to start with RAC? Use ReactiveCocoa has a KVO alternative Learn little by little its features and concepts
  • 4. RAC KVO Code NSString *const kCurrentUserKey = @“currentUser";
 
 [self removeObserver:self forKeyPath:kCurrentUserKey context:&kMyContext];
 … 
 [self addObserver:self forKeyPath:kCurrentUserKey options:NSKeyValueObservingOptionNew context:&kMyContext] - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
 {
 if([keyPath isEqualToString:kCurrentUserKey])
 {
 …
 }
 } - (void)setCurrentUser:(User *)user
 {
 if(_currentUser != user)
 {
 [self willChangeValueForKey:kCurrentUserKey];
 _currentUser = user;
 [self didChangeValueForKey:kCurrentUserKey];
 }
 } RAC(self, userNameLabel) = [RACObserve(self, userManager.currentUser.name) deliverOnMainThread];
  • 6. Simple binding Typical binding RAC(self, userName) = RACObserve(self, userManager.currentUser.lastName); userName is bound to userManager.currentUser.lastName. But what if userManager or currentUser is nil? RAC(self, userName, @“none”) = RACObserve(self, userManager.currentUser.lastName); Bonus: Don’t care whether objects in observed keypath are already allocated
  • 7. Observing changes only distinctUntilChanged RAC(self, userName) = [RACObserve(self, userManager.currentUser.lastName) distinctUntilChanged];
  • 8. Transforming map: RAC(self, userName) = [RACObserve(self, userManager.currentUser) map:^id(User *user) {
 return user.lastName;
 }]; RAC(self, userName) = [RACObserve(self, userManager.currentUser) map:^id(User *user) {
 return (user == nil ? nil : [NSString stringWithFormat:@"%@ %@", user.firstName, user.lastName]);
 }];
  • 9. Calling some code subscribeNext: [RACObserve(self, userManager.currentUser) subscribeNext:^(User *user) {
 if(user)
 {
 NSLog(@"%@", user.lastName);
 }
 }];
  • 10. Filtering filter: [[RACObserve(self, userManager.currentUser) filter:^BOOL(User *user) {
 return (user != nil) && user.admin;
 }] subscribeNext:^(User *user) {
 NSLog(@"%@ is admin", user.lastName);
 }];
  • 11. Specifying thread deliverOnMainThread RAC(self, userNameLabel.text) = [RACObserve(self, modelView.userName) deliverOnMainThread]; deliverOn: [[RACObserve(self, modelView.userName) deliverOn:self.scheduler] subscribeNext:^(User *user) {
 NSLog(@"I'm executed in a specific dispatch queue");
 }];
  • 12. Notification rac_addObserverForName: RAC(self, loggedIn) = [NSNotificationCenter.defaultCenter 
 rac_addObserverForName:kUserDidLogOutNotification object:nil]
 mapReplace:@NO];
  • 13. Combining combineLatest & reduce RAC(self, createEnabled) = [RACSignal
 combineLatest:@[RACObserve(self, password), RACObserve(self, passwordConfirmation)]
 reduce:^(NSString *password, NSString *passwordConfirm) {
 return @([passwordConfirm isEqualToString:password]);
 }];
  • 15. Parameters as id Most RAC methods return RACSignal and use id as parameters [RACObserve(self, userManager.currentUser) subscribeNext:^(id x) {
 NSLog(@"%@", ((User *)x).lastName);
 }]; ☟ [RACObserve(self, userManager.currentUser) subscribeNext:^(User *user) {
 NSLog(@"%@", user.lastName);
 }];
  • 16. Weakify/Strongify @weakify(self)
 [RACObserve(self, userManager.currentUser) subscribeNext:^(User *user) {
 @strongify(self)
 [self userChanged:user];
 }]; @weakify creates a new weakly referenced variable of the same type you pass in and assigns the original value to it @strongify creates a variable that matches the original variable but it exists in the local scope and assigns to it the variable created by @weakify
  • 17. Weakify/Strongify _weak id weakSelf = self;
 [RACObserve(self, userManager.currentUser) subscribeNext:^(User *user) {
 id strongSelf = weakSelf;
 [strongSelf userChanged:user];
 }]; @strongify in each async block No need for several @weakify(self)
  • 19. Pros Get rid of boilerplate code Less error prone
 (missing automaticallyNotifiesObserversOf<Property>?) Compatible with property refactoring (no more reference to keypath as string)
 If you change a property name manually, RAC code won’t compile anymore. Configuration is much easier, especially with multilevel keypath Memory management is rightly done out of the box Start to think functional, prepare for Swift
  • 20. Cons All values are object, BOOL are passed as NSNumber
 => isAdmin.boolValue 😢 Don’t forget deliverOnMainThread for UIKit components
  • 21. Warnings Don’t use RAC on intensive property change
 for example on Player.currentTime Don’t look at the stack!
 
 
 
 
 

  • 22. Warnings Don’t use RAC on intensive property change
 for example on Player.currentTime Don’t look at the stack!
 
 
 
 
 

  • 23.
  • 24. CocoaHeads Paris
 KVO with ReactiveCocoa Philippe Converset pconverset@autresphere.com @autresphere www.autresphere.com www.kidzik.com github.com/autresphere