RAC 综合一:模仿登录模块的网络请求
RAC(self.loginBtn,enabled) = [RACSignal combineLatest:@[_accountFiled.rac_textSignal,_pwdFiled.rac_textSignal] reduce:^id _Nullable(NSString *ac,NSString * pw){
return @(ac.length && pw.length);
}];
//包装一个命令 执行一些事情
//创建一个命令
RACCommand *command = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id _Nullable input) {
//密码加密
NSLog(@"拿到了:%@",input);
return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber> _Nonnull subscriber) {
// &&发送请求&& 获取登录结果!!
[subscriber sendNext:@"请求登录的数据"];
[subscriber sendCompleted];
return nil;
}];
}];
//获取命令中的一个信号源
[command.executionSignals.switchToLatest subscribeNext:^(id _Nullable x) {
NSLog(@"%@",x);
//
}];
//监听命令执行过程!
[[command.executing skip:1] subscribeNext:^(NSNumber * _Nullable x) {
NSLog(@"%@",x);
if ([x boolValue]) {
NSLog(@"显示菊花");
}else{
NSLog(@"关掉菊花");
}
}];
[[self.loginBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
NSLog(@"点击了登录按钮");
//处理登录事件
[command execute:@"账号密码"];
}];
仿照MVVM优化登录模块:
//MVVM M 模型 V视图+控制器 VM 视图模型
//VM 这就是MVVM架构的一个亮点!
首先创建一个登录的ViewModel
.h
@property (nonatomic,strong) NSString * account;
@property (nonatomic,strong) NSString * pwd;
@property (nonatomic,strong) RACSignal * loginEnableSignal;
//登录按钮命令
@property (nonatomic,strong) RACCommand *loginCommand;
.m
- (instancetype) init{
if (self = [super init]) {
//初始化 [self setUp]; }
return self;
}
- (void)setUp{
//根据文本框输入
_loginEnableSignal = [RACSignal combineLatest:@[RACObserve(self, account),RACObserve(self, pwd)] reduce:^id _Nullable (NSString * ac, NSString *pw){ return @(ac.length && pw.length); }];
//处理登录的命令 也可以用懒加载
_loginCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id _Nullable input) {
//密码加密
NSLog(@"拿到了:%@",input);
return [RACSignal createSignal:^RACDisposable * _Nullable(id _Nonnull subscriber) {
// &&发送请求&& 获取登录结果!!
[subscriber sendNext:@"请求登录的数据"];
[subscriber sendCompleted];
return nil;
}];
}];
//获取命令中的一个信号源
[_loginCommand.executionSignals.switchToLatest subscribeNext:^(id _Nullable x) {
NSLog(@"%@",x);
//
}];
//监听命令执行过程!
[[_loginCommand.executing skip:1] subscribeNext:^(NSNumber * _Nullable x) {
NSLog(@"%@",x);
if ([x boolValue]) {
NSLog(@"显示菊花");
}else{
NSLog(@"关掉菊花");
}
}];
}