SlideShare une entreprise Scribd logo
1  sur  30
Télécharger pour lire hors ligne
ReactiveCocoa	
@iacisclo
Programación imperativa.
• Describe detalladamente los
pasos a seguir.
• Continuos cambios de
estado.
• El orden de ejecución es vital.
• Muchos condicionales.
Programación declarativa
• Tu describes directamente los
resultados.
• El orden de ejecución no
importa.
• Sin apenas condicionales.
• No hay que estar pendiente
del estado.
ReactiveCocoa
• Compatible desde iOS 5.0+ y OS X 10.7+.
• Versión actual 2.2.4.
• Combina declarativa y funcional.
• Compatible con código no RAC.
¿Como?	
NSString *name = @"Belén";
NSString *surname = @“_Esteban”;
NSString *completeName = [name stringByAppendingString:surname];
surname = @“_Esteban, háztelo mirar”;
NSLog(@"%@",completeName);
El resultado sería “Belén_Esteban” pero con programación reactiva
sería “Belén_Esteban, háztelo mirar”.
[self.textField.rac_textSignal subscribeNext:^(NSString *value) {
self.lblValue.text = value;
}];
// Imperative
!
for (NSString *device in devices)
if ([device isEqualToString:@"iPod"]) {
self.name = device;
}
}
!
// Reactive
RAC(self, name) = [devices.rac_sequence.signal filter:^BOOL(NSString *device) {
return [device isEqualToString:@"iPod"];
}];
Clases
• RACStream
• RACSignal
• RACSubscriber
• RACSubject
• RACCommand
• RACMulticastConnection
• RACSequence
• RACDisposable
• RACSheduler
RACStream
• El padre de Todos.
• Es un conjunto de valores.
• Las señales contienen RACStreams.
• Los valores se recuperan de forma secuencial.
RACCommand
• Crea y se subscribe a una señal, generalmente
iniciada por UI.
self.button.rac_command = [[RACCommand alloc] initWithSignalBlock:^(id _) {
self.lblValue.text = @"Button tapped";
return [RACSignal empty];
}];
RACCommand *createAccount = [[RACCommand alloc]initWithEnabled:formValid signalBlock:^RACSignal *(id input) {
BOOL success = [IACClient logggin];
return [RACSignal return:@(success)];
}];
!
self.createButton.rac_command = createAccount;
RACSignal
• Envian 3 tipos de eventos: NEXT, ERROR, COMPLETED.
[signal subscribeNext:^(id x) {
NSLog(@"en la subscripción");
} error:^(NSError *error) {
NSLog(@"ha ocurrido un error.");
} completed:^{
NSLog(@"señal completa");
}];
RACSignal
RACSignal *executing = [racCommand.executing deliverOn:RACScheduler.mainThreadScheduler];
!
RACSignal *fieldTextColor = [executing map:^(NSNumber *x) {
return x.boolValue ? [UIColor lightGrayColor] : [UIColor blackColor];
}];
RACSignal *signal = @[@"iPhone",@"iPad",@"iMac",@"iPod"].rac_sequence.signal;
[[signal filter:^BOOL(NSString *value) {
return [value isEqualToString:@"iPad"];
}]subscribeNext:^(NSString *filterValue) {
self.lblValue.text = filterValue;
}];
RACSignal
!
RACSignal *formValid = [RACSignal
combineLatest:@[
self.firstNameField.rac_textSignal,
self.lastNameField.rac_textSignal,
self.emailField.rac_textSignal,
]
reduce:^(NSString *firstName,
NSString *lastName,
NSString *email){
return @(firstName.length > 0 &&
lastName.length > 0 &&
email.length > 0);
}];
RACSubject
• Señal que se puede controlar.
RACSubject *letters = [RACSubject subject];
[letters subscribeNext:^(NSString *letter) {
NSLog(@"%@",letter);
} completed:^{
NSLog(@"complete");
}];
[letters sendNext:@"A"];
[letters sendNext:@"B"];
[letters sendCompleted];
rac_liftSelector:withSignals:
!
self.delegate = [RACSubject subject];
!
[self.navigationController rac_liftSelector:@selector(pushViewController:animated:)
withSignals:self.delegate,[RACSignal return:@YES], nil];
!
/////
!
IACDetailViewController *detailVC = [self.storyboard
instantiateViewControllerWithIdentifier:@"IACDetailViewController"];
!
[self.delegate sendNext:detailVC];
!
RACSubscriber
• Todo objeto que espera o es capaz de
subscribirse a una señal
[[self saveImage:[UIImage imageNamed:@"image1"] withName:@"image1"]then:^RACSignal *{
NSLog(@"image guardada correctamente");
return nil;
}];
!
/////////
!
-(RACSignal *)saveImage:(UIImage *)image withName:(NSString *)name{
return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:@"savedImage.png"];
NSData *imageData = UIImagePNGRepresentation(image);
BOOL error = [imageData writeToFile:savedImagePath atomically:NO];
if (error) {
[subscriber sendError:nil];
}else{
[subscriber sendCompleted];
}
return nil;
}];
}
RACSequence
• Colecciones, señales guiadas.
RACSequence *devices = @[@"iPhone",@"iPad",@"iPod"].rac_sequence;
RACSequence *computers = @[@"iMac",@"Mac Mini",@"Macbook Air",@"Macbook
Pro"].rac_sequence;
RACSequence *concatenated = [devices concat:computers];
[concatenated.signal subscribeNext:^(id x) {
NSLog(@"%@",x);
}];
RACSequence
• Colecciones, señales guiadas.
RACSignal *devices = @[@"iPhone",@"iPad",@"iPod"].rac_sequence.signal;
RACSignal *sequenced = [[devices
doNext:^(NSString *device) {
NSLog(@"trabajamos con el objeto %@", device);
}]
then:^{
return @[@"iMac",@"Mac Mini",@"Macbook
Air",@"Macbook Pro"].rac_sequence.signal;
}];
[sequenced subscribeNext:^(NSString *computer) {
NSLog(@"%@",computer);
}];
do…
RACSignal *sequenced = [[[[devices
doNext:^(NSString *device) {
!
NSLog(@“antes de la subscripción %@“,device);
!
}]doError:^(NSError *error) {
!
NSLog(@"antes del error: %@", error);
!
}]doCompleted:^{
!
NSLog(@"señal antes de ser completada”);
!
}]then:^{
!
NSLog(@"señal ya completada”);
!
}];
RACDisposable
• Baja o limpieza de señales.
RACDisposable *subscription =
[self.textField.rac_textSignal
subscribeNext:^(NSString *text) {
self.lblValue.text = text;
}];
// en un futuro;
[subscription dispose];
Delegados
• Podemos sustituir delegados facilmente
self.textView.delegate = self;
[[self rac_signalForSelector:@selector(textViewDidChange:)fromProtocol:
@protocol(UITextViewDelegate)]subscribeNext:^(RACTuple *arguments) {
UITextView *textview = arguments.first;
}];
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Alert"
message:@"message"
delegate:self
cancelButtonTitle:@"cancel"
otherButtonTitles:@"ok", nil];
[alert show];
[alert.rac_buttonClickedSignal subscribeNext:^(NSNumber *index) {
NSLog(@"%@",index);
}];
Eventos de control
• UIControlEvetTouchDown
• UIControlEventTouchDownRepeat
• UIControlEventTouchDragInside
• UIControlEventTouchDragOutside
• UIControlEventTouchDragEnter
• UIControlEventTouchDragExit
• UIControlEventTouchUpInside
• UIControlEventTouchUpOutside
• UIControlEventTouchCancel
• UIControlEventValueChanged
• UIControlEventEditingDidBegin
• UIControlEventEditingChanged
• UIControlEventEditingDidEnd
• UIControlEventEditingDidEndOnExit
• UIControlEventAllTouchEvents
• UIControlEventAllEditingEvents
• UIControlEventApplicationReserved
• UIControlEventSystemReserved
Eventos de control
[[stepper rac_signalForControlEvents:UIControlEventAllTouchEvents]
subscribeNext:^(UIStepper *stepper) {
self.lblValue.text = [NSString stringWithFormat:@"%f",stepper.value];
}];
RAC(self.textField, textColor) = [[self.textField rac_signalForControlEvents:
UIControlEventAllEvents]map:^id(UITextField *textfield) {
if (textfield.text.length >3) {
return [UIColor blackColor];
}else{
return [UIColor redColor];
}
}];
RACSheduler
• GCD en RAC.
[[self.textField.rac_textSignal deliverOn:[RACScheduler mainThreadScheduler]]
subscribeNext:^(NSString *value) {
self.lblValue.text = value;
}];
RACScheduler *scheduler = [RACScheduler
schedulerWithPriority:RACSchedulerPriorityBackground];
[[RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
return nil;
}]subscribeOn:scheduler];
RACSheduler
//////
!
[[[self signalForLoadingImage:tweet.profileImageUrl]
deliverOn:[RACScheduler mainThreadScheduler]]
subscribeNext:^(UIImage *image) {
cell.twitterAvatarView.image = image;
}];
!
///////
!
-(RACSignal *)signalForLoadingImage:(NSString *)imageUrl {
RACScheduler *scheduler = [RACScheduler
schedulerWithPriority:RACSchedulerPriorityBackground];
return [[RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber)
{
NSData *data = [NSData dataWithContentsOfURL:[NSURL
URLWithString:imageUrl]];
UIImage *image = [UIImage imageWithData:data];
[subscriber sendNext:image];
[subscriber sendCompleted];
return nil;
}]subscribeOn:scheduler];
}
Memoria
__weak ViewController *bself = self;
[[self.searchText.rac_textSignal
map:^id(NSString *text) {
return [self isValidSearchText:text] ?
[UIColor whiteColor] : [UIColor yellowColor];
}]
subscribeNext:^(UIColor *color) {
bself.searchText.backgroundColor = color;
}];
Memoria
#import "RACEXTScope.h"
!
!
@weakify(self)
[[self.searchText.rac_textSignal
map:^id(NSString *text) {
return [self isValidSearchText:text] ?
[UIColor whiteColor] : [UIColor yellowColor];
}]
subscribeNext:^(UIColor *color) {
@strongify(self)
self.searchText.backgroundColor = color;
}];
RACObserve(TARGET, KEYPATH)
@weakify(self)
[RACObserve(self, modelArray) subscribeNext:^(id x) {
@strongify(self)
[self.collectionView reloadData];
}];
[[[RACObserve(photoModel, imageData)filter:^BOOL(id value) {
return value != nil;
}]map:^id(id value) {
return [UIImage imageWithData:value];
}]setKeyPath:@keypath(self.imageView, image)
onObject:self.imageView];
RAC(TARGET, …)
RAC(self,dateAdded) = [RACObserve(self.model,dateAdded)map:^(NSDate*date){
return [[ViewModel dateFormatter] stringFromDate:date];
}];
!
RAC(self, name) = self.textField.rac_textSignal;
return;

Contenu connexe

Tendances

ReactiveCocoa and Swift, Better Together
ReactiveCocoa and Swift, Better TogetherReactiveCocoa and Swift, Better Together
ReactiveCocoa and Swift, Better TogetherColin Eberhardt
 
Intro to ReactiveCocoa
Intro to ReactiveCocoaIntro to ReactiveCocoa
Intro to ReactiveCocoakleneau
 
An Introduction to Reactive Cocoa
An Introduction to Reactive CocoaAn Introduction to Reactive Cocoa
An Introduction to Reactive CocoaSmartLogic
 
The Ring programming language version 1.8 book - Part 26 of 202
The Ring programming language version 1.8 book - Part 26 of 202The Ring programming language version 1.8 book - Part 26 of 202
The Ring programming language version 1.8 book - Part 26 of 202Mahmoud Samir Fayed
 
Introduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaIntroduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaFlorent Pillet
 
Angular and The Case for RxJS
Angular and The Case for RxJSAngular and The Case for RxJS
Angular and The Case for RxJSSandi Barr
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript FunctionsColin DeCarlo
 
Java script advance-auroskills (2)
Java script advance-auroskills (2)Java script advance-auroskills (2)
Java script advance-auroskills (2)BoneyGawande
 
Java script – basic auroskills (2)
Java script – basic   auroskills (2)Java script – basic   auroskills (2)
Java script – basic auroskills (2)BoneyGawande
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJSBrainhub
 
Swiss army knife Spring
Swiss army knife SpringSwiss army knife Spring
Swiss army knife SpringMario Fusco
 
JavaOne 2013: Java 8 - The Good Parts
JavaOne 2013: Java 8 - The Good PartsJavaOne 2013: Java 8 - The Good Parts
JavaOne 2013: Java 8 - The Good PartsKonrad Malawski
 
The Ring programming language version 1.9 book - Part 28 of 210
The Ring programming language version 1.9 book - Part 28 of 210The Ring programming language version 1.9 book - Part 28 of 210
The Ring programming language version 1.9 book - Part 28 of 210Mahmoud Samir Fayed
 
LinkedIn TBC JavaScript 100: Functions
 LinkedIn TBC JavaScript 100: Functions LinkedIn TBC JavaScript 100: Functions
LinkedIn TBC JavaScript 100: FunctionsAdam Crabtree
 
VPN Access Runbook
VPN Access RunbookVPN Access Runbook
VPN Access RunbookTaha Shakeel
 
Angular & RXJS: examples and use cases
Angular & RXJS: examples and use casesAngular & RXJS: examples and use cases
Angular & RXJS: examples and use casesFabio Biondi
 
What is new in java 8 concurrency
What is new in java 8 concurrencyWhat is new in java 8 concurrency
What is new in java 8 concurrencykshanth2101
 

Tendances (20)

ReactiveCocoa and Swift, Better Together
ReactiveCocoa and Swift, Better TogetherReactiveCocoa and Swift, Better Together
ReactiveCocoa and Swift, Better Together
 
Intro to ReactiveCocoa
Intro to ReactiveCocoaIntro to ReactiveCocoa
Intro to ReactiveCocoa
 
An Introduction to Reactive Cocoa
An Introduction to Reactive CocoaAn Introduction to Reactive Cocoa
An Introduction to Reactive Cocoa
 
The Ring programming language version 1.8 book - Part 26 of 202
The Ring programming language version 1.8 book - Part 26 of 202The Ring programming language version 1.8 book - Part 26 of 202
The Ring programming language version 1.8 book - Part 26 of 202
 
Introduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaIntroduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoa
 
SQL Functions
SQL FunctionsSQL Functions
SQL Functions
 
Angular and The Case for RxJS
Angular and The Case for RxJSAngular and The Case for RxJS
Angular and The Case for RxJS
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
 
Java script advance-auroskills (2)
Java script advance-auroskills (2)Java script advance-auroskills (2)
Java script advance-auroskills (2)
 
Java script – basic auroskills (2)
Java script – basic   auroskills (2)Java script – basic   auroskills (2)
Java script – basic auroskills (2)
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJS
 
Swiss army knife Spring
Swiss army knife SpringSwiss army knife Spring
Swiss army knife Spring
 
JavaOne 2013: Java 8 - The Good Parts
JavaOne 2013: Java 8 - The Good PartsJavaOne 2013: Java 8 - The Good Parts
JavaOne 2013: Java 8 - The Good Parts
 
Java script
Java scriptJava script
Java script
 
The Ring programming language version 1.9 book - Part 28 of 210
The Ring programming language version 1.9 book - Part 28 of 210The Ring programming language version 1.9 book - Part 28 of 210
The Ring programming language version 1.9 book - Part 28 of 210
 
LinkedIn TBC JavaScript 100: Functions
 LinkedIn TBC JavaScript 100: Functions LinkedIn TBC JavaScript 100: Functions
LinkedIn TBC JavaScript 100: Functions
 
VPN Access Runbook
VPN Access RunbookVPN Access Runbook
VPN Access Runbook
 
Reactive Java (33rd Degree)
Reactive Java (33rd Degree)Reactive Java (33rd Degree)
Reactive Java (33rd Degree)
 
Angular & RXJS: examples and use cases
Angular & RXJS: examples and use casesAngular & RXJS: examples and use cases
Angular & RXJS: examples and use cases
 
What is new in java 8 concurrency
What is new in java 8 concurrencyWhat is new in java 8 concurrency
What is new in java 8 concurrency
 

Similaire à Reactive cocoa

Functional Reactive Programming (CocoaHeads Bratislava)
Functional Reactive Programming (CocoaHeads Bratislava)Functional Reactive Programming (CocoaHeads Bratislava)
Functional Reactive Programming (CocoaHeads Bratislava)Michal Grman
 
Functional Reactive Programming dengan ReactiveCocoa
Functional Reactive Programming dengan ReactiveCocoaFunctional Reactive Programming dengan ReactiveCocoa
Functional Reactive Programming dengan ReactiveCocoaDidiet Noor
 
NyaruDBにゃるものを使ってみた話 (+Realm比較)
NyaruDBにゃるものを使ってみた話 (+Realm比較)NyaruDBにゃるものを使ってみた話 (+Realm比較)
NyaruDBにゃるものを使ってみた話 (+Realm比較)Masaki Oshikawa
 
mobile in the cloud with diamonds. improved.
mobile in the cloud with diamonds. improved.mobile in the cloud with diamonds. improved.
mobile in the cloud with diamonds. improved.Oleg Shanyuk
 
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
 
Talk KVO with rac by Philippe Converset
Talk KVO with rac by Philippe ConversetTalk KVO with rac by Philippe Converset
Talk KVO with rac by Philippe ConversetCocoaHeads France
 
Pieter De Baets - An introduction to React Native
Pieter De Baets - An introduction to React NativePieter De Baets - An introduction to React Native
Pieter De Baets - An introduction to React Nativetlv-ios-dev
 
JavaScript Editions ES7, ES8 and ES9 vs V8
JavaScript Editions ES7, ES8 and ES9 vs V8JavaScript Editions ES7, ES8 and ES9 vs V8
JavaScript Editions ES7, ES8 and ES9 vs V8Rafael Casuso Romate
 
Hızlı Cocoa Geliştirme (Develop your next cocoa app faster!)
Hızlı Cocoa Geliştirme (Develop your next cocoa app faster!)Hızlı Cocoa Geliştirme (Develop your next cocoa app faster!)
Hızlı Cocoa Geliştirme (Develop your next cocoa app faster!)Sarp Erdag
 
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
 
The Ring programming language version 1.8 book - Part 90 of 202
The Ring programming language version 1.8 book - Part 90 of 202The Ring programming language version 1.8 book - Part 90 of 202
The Ring programming language version 1.8 book - Part 90 of 202Mahmoud Samir Fayed
 
Better Open Source Enterprise C++ Web Services
Better Open Source Enterprise C++ Web ServicesBetter Open Source Enterprise C++ Web Services
Better Open Source Enterprise C++ Web ServicesWSO2
 

Similaire à Reactive cocoa (20)

Functional Reactive Programming (CocoaHeads Bratislava)
Functional Reactive Programming (CocoaHeads Bratislava)Functional Reactive Programming (CocoaHeads Bratislava)
Functional Reactive Programming (CocoaHeads Bratislava)
 
Reactive Cocoa
Reactive CocoaReactive Cocoa
Reactive Cocoa
 
Functional Reactive Programming dengan ReactiveCocoa
Functional Reactive Programming dengan ReactiveCocoaFunctional Reactive Programming dengan ReactiveCocoa
Functional Reactive Programming dengan ReactiveCocoa
 
NyaruDBにゃるものを使ってみた話 (+Realm比較)
NyaruDBにゃるものを使ってみた話 (+Realm比較)NyaruDBにゃるものを使ってみた話 (+Realm比較)
NyaruDBにゃるものを使ってみた話 (+Realm比較)
 
mobile in the cloud with diamonds. improved.
mobile in the cloud with diamonds. improved.mobile in the cloud with diamonds. improved.
mobile in the cloud with diamonds. improved.
 
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"
 
Sqlapi0.1
Sqlapi0.1Sqlapi0.1
Sqlapi0.1
 
Modern JS with ES6
Modern JS with ES6Modern JS with ES6
Modern JS with ES6
 
Talk KVO with rac by Philippe Converset
Talk KVO with rac by Philippe ConversetTalk KVO with rac by Philippe Converset
Talk KVO with rac by Philippe Converset
 
Pieter De Baets - An introduction to React Native
Pieter De Baets - An introduction to React NativePieter De Baets - An introduction to React Native
Pieter De Baets - An introduction to React Native
 
Day 1
Day 1Day 1
Day 1
 
JavaScript Editions ES7, ES8 and ES9 vs V8
JavaScript Editions ES7, ES8 and ES9 vs V8JavaScript Editions ES7, ES8 and ES9 vs V8
JavaScript Editions ES7, ES8 and ES9 vs V8
 
Hızlı Cocoa Geliştirme (Develop your next cocoa app faster!)
Hızlı Cocoa Geliştirme (Develop your next cocoa app faster!)Hızlı Cocoa Geliştirme (Develop your next cocoa app faster!)
Hızlı Cocoa Geliştirme (Develop your next cocoa app faster!)
 
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.
 
C++ Functions
C++ FunctionsC++ Functions
C++ Functions
 
angular fundamentals.pdf
angular fundamentals.pdfangular fundamentals.pdf
angular fundamentals.pdf
 
Runtime
RuntimeRuntime
Runtime
 
FMDB - SLC-Cocoaheads
FMDB - SLC-CocoaheadsFMDB - SLC-Cocoaheads
FMDB - SLC-Cocoaheads
 
The Ring programming language version 1.8 book - Part 90 of 202
The Ring programming language version 1.8 book - Part 90 of 202The Ring programming language version 1.8 book - Part 90 of 202
The Ring programming language version 1.8 book - Part 90 of 202
 
Better Open Source Enterprise C++ Web Services
Better Open Source Enterprise C++ Web ServicesBetter Open Source Enterprise C++ Web Services
Better Open Source Enterprise C++ Web Services
 

Dernier

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
 
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
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
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
 
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
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
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
 

Dernier (20)

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 ...
 
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
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
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
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
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
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
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...
 
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 ...
 
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
 

Reactive cocoa

  • 2. Programación imperativa. • Describe detalladamente los pasos a seguir. • Continuos cambios de estado. • El orden de ejecución es vital. • Muchos condicionales.
  • 3. Programación declarativa • Tu describes directamente los resultados. • El orden de ejecución no importa. • Sin apenas condicionales. • No hay que estar pendiente del estado.
  • 4. ReactiveCocoa • Compatible desde iOS 5.0+ y OS X 10.7+. • Versión actual 2.2.4. • Combina declarativa y funcional. • Compatible con código no RAC.
  • 5. ¿Como? NSString *name = @"Belén"; NSString *surname = @“_Esteban”; NSString *completeName = [name stringByAppendingString:surname]; surname = @“_Esteban, háztelo mirar”; NSLog(@"%@",completeName); El resultado sería “Belén_Esteban” pero con programación reactiva sería “Belén_Esteban, háztelo mirar”.
  • 7. // Imperative ! for (NSString *device in devices) if ([device isEqualToString:@"iPod"]) { self.name = device; } } ! // Reactive RAC(self, name) = [devices.rac_sequence.signal filter:^BOOL(NSString *device) { return [device isEqualToString:@"iPod"]; }];
  • 8. Clases • RACStream • RACSignal • RACSubscriber • RACSubject • RACCommand • RACMulticastConnection • RACSequence • RACDisposable • RACSheduler
  • 9. RACStream • El padre de Todos. • Es un conjunto de valores. • Las señales contienen RACStreams. • Los valores se recuperan de forma secuencial.
  • 10. RACCommand • Crea y se subscribe a una señal, generalmente iniciada por UI. self.button.rac_command = [[RACCommand alloc] initWithSignalBlock:^(id _) { self.lblValue.text = @"Button tapped"; return [RACSignal empty]; }]; RACCommand *createAccount = [[RACCommand alloc]initWithEnabled:formValid signalBlock:^RACSignal *(id input) { BOOL success = [IACClient logggin]; return [RACSignal return:@(success)]; }]; ! self.createButton.rac_command = createAccount;
  • 11. RACSignal • Envian 3 tipos de eventos: NEXT, ERROR, COMPLETED. [signal subscribeNext:^(id x) { NSLog(@"en la subscripción"); } error:^(NSError *error) { NSLog(@"ha ocurrido un error."); } completed:^{ NSLog(@"señal completa"); }];
  • 12. RACSignal RACSignal *executing = [racCommand.executing deliverOn:RACScheduler.mainThreadScheduler]; ! RACSignal *fieldTextColor = [executing map:^(NSNumber *x) { return x.boolValue ? [UIColor lightGrayColor] : [UIColor blackColor]; }]; RACSignal *signal = @[@"iPhone",@"iPad",@"iMac",@"iPod"].rac_sequence.signal; [[signal filter:^BOOL(NSString *value) { return [value isEqualToString:@"iPad"]; }]subscribeNext:^(NSString *filterValue) { self.lblValue.text = filterValue; }];
  • 13. RACSignal ! RACSignal *formValid = [RACSignal combineLatest:@[ self.firstNameField.rac_textSignal, self.lastNameField.rac_textSignal, self.emailField.rac_textSignal, ] reduce:^(NSString *firstName, NSString *lastName, NSString *email){ return @(firstName.length > 0 && lastName.length > 0 && email.length > 0); }];
  • 14. RACSubject • Señal que se puede controlar. RACSubject *letters = [RACSubject subject]; [letters subscribeNext:^(NSString *letter) { NSLog(@"%@",letter); } completed:^{ NSLog(@"complete"); }]; [letters sendNext:@"A"]; [letters sendNext:@"B"]; [letters sendCompleted];
  • 15. rac_liftSelector:withSignals: ! self.delegate = [RACSubject subject]; ! [self.navigationController rac_liftSelector:@selector(pushViewController:animated:) withSignals:self.delegate,[RACSignal return:@YES], nil]; ! ///// ! IACDetailViewController *detailVC = [self.storyboard instantiateViewControllerWithIdentifier:@"IACDetailViewController"]; ! [self.delegate sendNext:detailVC]; !
  • 16. RACSubscriber • Todo objeto que espera o es capaz de subscribirse a una señal [[self saveImage:[UIImage imageNamed:@"image1"] withName:@"image1"]then:^RACSignal *{ NSLog(@"image guardada correctamente"); return nil; }]; ! ///////// ! -(RACSignal *)saveImage:(UIImage *)image withName:(NSString *)name{ return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:@"savedImage.png"]; NSData *imageData = UIImagePNGRepresentation(image); BOOL error = [imageData writeToFile:savedImagePath atomically:NO]; if (error) { [subscriber sendError:nil]; }else{ [subscriber sendCompleted]; } return nil; }]; }
  • 17. RACSequence • Colecciones, señales guiadas. RACSequence *devices = @[@"iPhone",@"iPad",@"iPod"].rac_sequence; RACSequence *computers = @[@"iMac",@"Mac Mini",@"Macbook Air",@"Macbook Pro"].rac_sequence; RACSequence *concatenated = [devices concat:computers]; [concatenated.signal subscribeNext:^(id x) { NSLog(@"%@",x); }];
  • 18. RACSequence • Colecciones, señales guiadas. RACSignal *devices = @[@"iPhone",@"iPad",@"iPod"].rac_sequence.signal; RACSignal *sequenced = [[devices doNext:^(NSString *device) { NSLog(@"trabajamos con el objeto %@", device); }] then:^{ return @[@"iMac",@"Mac Mini",@"Macbook Air",@"Macbook Pro"].rac_sequence.signal; }]; [sequenced subscribeNext:^(NSString *computer) { NSLog(@"%@",computer); }];
  • 19. do… RACSignal *sequenced = [[[[devices doNext:^(NSString *device) { ! NSLog(@“antes de la subscripción %@“,device); ! }]doError:^(NSError *error) { ! NSLog(@"antes del error: %@", error); ! }]doCompleted:^{ ! NSLog(@"señal antes de ser completada”); ! }]then:^{ ! NSLog(@"señal ya completada”); ! }];
  • 20. RACDisposable • Baja o limpieza de señales. RACDisposable *subscription = [self.textField.rac_textSignal subscribeNext:^(NSString *text) { self.lblValue.text = text; }]; // en un futuro; [subscription dispose];
  • 21. Delegados • Podemos sustituir delegados facilmente self.textView.delegate = self; [[self rac_signalForSelector:@selector(textViewDidChange:)fromProtocol: @protocol(UITextViewDelegate)]subscribeNext:^(RACTuple *arguments) { UITextView *textview = arguments.first; }]; UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"message" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"ok", nil]; [alert show]; [alert.rac_buttonClickedSignal subscribeNext:^(NSNumber *index) { NSLog(@"%@",index); }];
  • 22. Eventos de control • UIControlEvetTouchDown • UIControlEventTouchDownRepeat • UIControlEventTouchDragInside • UIControlEventTouchDragOutside • UIControlEventTouchDragEnter • UIControlEventTouchDragExit • UIControlEventTouchUpInside • UIControlEventTouchUpOutside • UIControlEventTouchCancel • UIControlEventValueChanged • UIControlEventEditingDidBegin • UIControlEventEditingChanged • UIControlEventEditingDidEnd • UIControlEventEditingDidEndOnExit • UIControlEventAllTouchEvents • UIControlEventAllEditingEvents • UIControlEventApplicationReserved • UIControlEventSystemReserved
  • 23. Eventos de control [[stepper rac_signalForControlEvents:UIControlEventAllTouchEvents] subscribeNext:^(UIStepper *stepper) { self.lblValue.text = [NSString stringWithFormat:@"%f",stepper.value]; }]; RAC(self.textField, textColor) = [[self.textField rac_signalForControlEvents: UIControlEventAllEvents]map:^id(UITextField *textfield) { if (textfield.text.length >3) { return [UIColor blackColor]; }else{ return [UIColor redColor]; } }];
  • 24. RACSheduler • GCD en RAC. [[self.textField.rac_textSignal deliverOn:[RACScheduler mainThreadScheduler]] subscribeNext:^(NSString *value) { self.lblValue.text = value; }]; RACScheduler *scheduler = [RACScheduler schedulerWithPriority:RACSchedulerPriorityBackground]; [[RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) { return nil; }]subscribeOn:scheduler];
  • 25. RACSheduler ////// ! [[[self signalForLoadingImage:tweet.profileImageUrl] deliverOn:[RACScheduler mainThreadScheduler]] subscribeNext:^(UIImage *image) { cell.twitterAvatarView.image = image; }]; ! /////// ! -(RACSignal *)signalForLoadingImage:(NSString *)imageUrl { RACScheduler *scheduler = [RACScheduler schedulerWithPriority:RACSchedulerPriorityBackground]; return [[RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) { NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrl]]; UIImage *image = [UIImage imageWithData:data]; [subscriber sendNext:image]; [subscriber sendCompleted]; return nil; }]subscribeOn:scheduler]; }
  • 26. Memoria __weak ViewController *bself = self; [[self.searchText.rac_textSignal map:^id(NSString *text) { return [self isValidSearchText:text] ? [UIColor whiteColor] : [UIColor yellowColor]; }] subscribeNext:^(UIColor *color) { bself.searchText.backgroundColor = color; }];
  • 27. Memoria #import "RACEXTScope.h" ! ! @weakify(self) [[self.searchText.rac_textSignal map:^id(NSString *text) { return [self isValidSearchText:text] ? [UIColor whiteColor] : [UIColor yellowColor]; }] subscribeNext:^(UIColor *color) { @strongify(self) self.searchText.backgroundColor = color; }];
  • 28. RACObserve(TARGET, KEYPATH) @weakify(self) [RACObserve(self, modelArray) subscribeNext:^(id x) { @strongify(self) [self.collectionView reloadData]; }]; [[[RACObserve(photoModel, imageData)filter:^BOOL(id value) { return value != nil; }]map:^id(id value) { return [UIImage imageWithData:value]; }]setKeyPath:@keypath(self.imageView, image) onObject:self.imageView];
  • 29. RAC(TARGET, …) RAC(self,dateAdded) = [RACObserve(self.model,dateAdded)map:^(NSDate*date){ return [[ViewModel dateFormatter] stringFromDate:date]; }]; ! RAC(self, name) = self.textField.rac_textSignal;