5-4RAC-MVVM架构设计

登录界面xib设置

111.png
//  MVC  -- 逻辑非常清晰!!
//  MVVM --  M 模型  V 视图+控制器  VM:视图模型
//  VM(给C瘦身!!): 这就是MVVM架构的一个亮点!!代替控制器做N多的逻辑处理!!

#import "ViewController.h"

#import 
#import "LoginViewModel.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITextField *accountFiled;

@property (weak, nonatomic) IBOutlet UITextField *pwdFiled;

@property (weak, nonatomic) IBOutlet UIButton *loginBtn;

/** VM  */
@property(nonatomic,strong) LoginViewModel * loginVM;

@end

@implementation ViewController

-(LoginViewModel *)loginVM
{
    //有效避免出错!!
    if (nil == _loginVM) {
        _loginVM = [[LoginViewModel alloc]init];
        
    }
    return _loginVM;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    //1.给模型的账号&&密码绑定信号!!
    RAC(self.loginVM,account) = _accountFiled.rac_textSignal;
    RAC(self.loginVM,pwd) = _pwdFiled.rac_textSignal;
    //2.设置按钮
    RAC(_loginBtn,enabled) = self.loginVM.loginEnableSignal;
    //3.监听登录按钮的点击
    [[_loginBtn rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
        //处理登录事件
        [self.loginVM.loginCommand execute:@"账号密码"];
    }];
    
    
    
    
}

#import 
#import 

@interface LoginViewModel : NSObject

/** 账号&&密码  */
@property(nonatomic,strong)NSString * account;
@property(nonatomic,strong)NSString * pwd;

/**  处理登录按钮能否点击的信号 */
@property(nonatomic,strong)RACSignal * loginEnableSignal;

/** 登录按钮命令  */
@property(nonatomic,strong)RACCommand * loginCommand;

@end


#import "LoginViewModel.h"

@implementation LoginViewModel

-(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 * account,NSString * pwd){
        return @(account.length && pwd.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) {
        
        if ([x boolValue]) {
            //正在执行
            NSLog(@"显示菊花!!");
        }else{
            NSLog(@"干掉菊花!!");
        }
        
    }];
    
}

@end

你可能感兴趣的:(5-4RAC-MVVM架构设计)