MVVM+RAC Demo

#import "ViewController.h"
#import "LoginViewModel.h"

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

@property (nonatomic, strong) LoginViewModel *loginVM;

@end

@implementation ViewController

- (LoginViewModel *)loginVM{
    if (_loginVM == nil) {
        _loginVM = [[LoginViewModel alloc]init];
    }
    return _loginVM;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    RAC(_loginVM,account) = _accountFiled.rac_textSignal;
    RAC(_loginVM,pwd) = _pwdField.rac_textSignal;
    RAC(_loginBtn,enabled) = _loginVM.loginEnableSiganl;
    
    // 监听登录按钮点击
    [[_loginBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        NSLog(@"点击登录按钮");
        // 处理登录事件
        [_loginVM.loginCommand execute:nil];
        
    }];
}

@end
#import 
#import "ReactiveCocoa.h"

@interface LoginViewModel : NSObject

// 保存登录界面的账号和密码
/** 账号 */
@property (nonatomic, strong) NSString *account;
@property (nonatomic, strong) NSString *pwd;

// 处理登录按钮是否允许点击
@property (nonatomic, strong, readonly) RACSignal *loginEnableSiganl;


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

@end
#import "LoginViewModel.h"

@implementation LoginViewModel

- (instancetype)init{
    self = [super init];
    if (self) {
        [self setUp];
    }
    return self;
}

- (void)setUp{
     // 1.处理登录点击的信号
    _loginEnableSiganl = [RACSignal combineLatest:@[RACObserve(self, account),RACObserve(self, pwd)] reduce:^id(NSString *account,NSString *pwd){
        return @(account.length && pwd.length);
    }];
     // 2.处理登录点击命令
    _loginCommand = [[RACCommand alloc]initWithSignalBlock:^RACSignal *(id input) {
        NSLog(@"发送登录请求");
        return [RACSignal createSignal:^RACDisposable *(id subscriber) {
            [subscriber sendNext:@"请求回来的数据"];
            [subscriber sendCompleted];
            return nil;
        }];
    }];
    // 3.处理登录请求返回的结果
    [_loginCommand.executionSignals.switchToLatest subscribeNext:^(id x) {
        //转模型等等
        NSLog(@"%@",x);
    }];
    
    // 4.处理登录执行过程
    [[_loginCommand.executing skip:1] subscribeNext:^(id x) {
        
        if ([x boolValue] == YES) {
            // 正在执行
            NSLog(@"正在执行");
            // 显示蒙版
        }else{
            // 执行完成
            // 隐藏蒙版
            NSLog(@"执行完成");
        }
        
    }];
}

@end

你可能感兴趣的:(MVVM+RAC Demo)