OC的MVVM的數(shù)據(jù)雙向綁定改造

目標(biāo)

OC改造為MVVM設(shè)計(jì)模式,并且實(shí)現(xiàn)VM與View和Model的數(shù)據(jù)雙向綁定。使用ReactiveObjC來(lái)進(jìn)行改造。想進(jìn)一步了解ReactiveObjC可以參考:
https://blog.devtang.com/2014/02/11/reactivecocoa-introduction/

https://cloud.tencent.com/developer/article/1017790

http://www.itdecent.cn/p/87ef6720a096

項(xiàng)目結(jié)構(gòu)

本次可能我會(huì)淡化Model,而是直接在VM上定義了Model相關(guān)。主要關(guān)注VM和View的數(shù)據(jù)雙向綁定。
功能是,登錄界面,有一個(gè)username TF,一個(gè)password TF,一個(gè)登錄按鈕:
ReactiveLogin-UIViewController

@interface ReactiveLogin ()
<UITextFieldDelegate>
{
    
}

@property(nonatomic) UIImageView *headImgV;
@property(nonatomic) UITextField *usernameTf;
@property(nonatomic) UITextField *pwdTf;
@property(nonatomic) UIButton *loginBtn;

@property(nonatomic) UserVM *userVM;
@end

@implementation ReactiveLogin

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setNavWithTitle:@"Login" leftImage:@"arrow" leftTitle:nil leftAction:nil rightImage:nil rightTitle:nil rightAction:nil];
    [self setupUI];
    [self bindVM];
}

- (void)setupUI{
    [self.view addSubview:self.headImgV];
    [self.view addSubview:self.usernameTf];
    [self.view addSubview:self.pwdTf];
    [self.view addSubview:self.loginBtn];
    
    [self.headImgV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(100);
        make.centerX.mas_equalTo(0);
        make.width.height.mas_equalTo(80);
    }];
    [self.usernameTf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.headImgV.mas_bottom).mas_offset(14);
        make.centerX.mas_equalTo(0);
        make.width.mas_equalTo(200);
        make.height.mas_equalTo(44);
    }];
    
    [self.pwdTf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.usernameTf.mas_bottom).mas_offset(10);
        make.centerX.mas_equalTo(0);
        make.width.height.equalTo(self.usernameTf);
    }];
    [self.loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.pwdTf.mas_bottom).mas_offset(14);
        make.centerX.mas_equalTo(0);
        make.width.height.equalTo(self.usernameTf);
    }];
}

- (void)bindVM{
    self.userVM = [[UserVM alloc] init];
    
    @weakify(self)
    [[self rac_signalForSelector:@selector(textFieldShouldReturn:) fromProtocol:@protocol(UITextFieldDelegate)] subscribeNext:^(RACTuple * _Nullable x) {
        NSLog(@"%@",x);
        UITextField *tf = (UITextField *)x[0];
        [tf resignFirstResponder];
    }];
    
    RAC(self.userVM,username) = self.usernameTf.rac_textSignal;
    RAC(self.userVM,pwd) = self.pwdTf.rac_textSignal;
    
    
    [[RACSignal combineLatest:@[self.usernameTf.rac_textSignal, self.pwdTf.rac_textSignal] reduce:^id _Nonnull(NSString *username, NSString *password){
        return @(username.length && password.length);
    }] subscribeNext:^(id  _Nullable x) {
        NSLog(@"combineLatest>>>%@ %@",x,[NSThread currentThread]);
        BOOL enable = [x boolValue];
        self.loginBtn.enabled = enable;
        if(enable){
            [self.loginBtn setBackgroundColor:[UIColor greenColor]];
        }else{
            [self.loginBtn setBackgroundColor:[UIColor grayColor]];
        }
    }];
    
    [[self.loginBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self.userVM.loginCommand execute:nil];
    }];
    [self.userVM.loginCommand.executing subscribeNext:^(NSNumber * _Nullable x) {
        BOOL ret = [x boolValue];
        ret?[PublicFunction showNoHiddenLoading:@""]:[PublicFunction hiddenHUD];
    }];
    
    [self.userVM.loginCommand.executionSignals subscribeNext:^(RACSignal  *x) {
        
        [x subscribeNext:^(id  _Nullable x) {
            NSLog(@"login succ>>>%@",x);
        }];
        [x subscribeCompleted:^{
            NSLog(@"login completed");
        }];
        [x subscribeError:^(NSError * _Nullable error) {
            NSLog(@"login errors>>>%@",x);
        }];
        
//        [x subscribeNext:^(id  _Nullable x) {
//            NSLog(@"login succ>>>%@",x);
//        } completed:^{
//            NSLog(@"login completed");
//        }];
        
    }];
    [self.userVM.loginCommand.errors subscribeNext:^(NSError * _Nullable x) {
        NSLog(@"errors>>>%@",x);
    }];
//    [self.userVM.loginCommand.executionSignals.switchToLatest subscribeNext:^(id  _Nullable x) {
//        NSLog(@"login succ>>>%@",x);
//    } error:^(NSError * _Nullable error) {
//        NSLog(@"login error>>>%@",error);
//    } completed:^{
//        NSLog(@"login completed");
//    }];
//    [self.userVM.loginCommand.executionSignals.switchToLatest subscribeError:^(NSError * _Nullable error) {
//        NSLog(@"login error>>>%@",error);
//    }];
    
    [RACObserve(self.userVM, headUrl) subscribeNext:^(id  _Nullable x) {
        @strongify(self)
//        self.headImgV.image = [UIImage imageNamed:x];
        NSLog(@"headUrl>>>%@",x);
        self.headImgV.backgroundColor = [UIColor redColor];
        if([x isEqualToString:@"blue"]){
            self.headImgV.backgroundColor = [UIColor blueColor];
        }
        
    }];
}

#pragma -mark getting or setting

- (UIImageView *)headImgV{
    if(!_headImgV){
        _headImgV = [[UIImageView alloc] init];
        _headImgV.backgroundColor = [UIColor redColor];
    }
    return _headImgV;
}

- (UITextField *)usernameTf{
    if(!_usernameTf){
        _usernameTf = [[UITextField alloc] init];
        _usernameTf.layer.borderWidth = 1;
        _usernameTf.delegate = self;
    }
    return _usernameTf;
}

- (UITextField *)pwdTf{
    if(!_pwdTf){
        _pwdTf = [[UITextField alloc] init];
        _pwdTf.layer.borderWidth = 1;
        _pwdTf.delegate = self;
    }
    return _pwdTf;
}

- (UIButton *)loginBtn{
    if(!_loginBtn){
        _loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_loginBtn setBackgroundColor:[UIColor greenColor]];
        [_loginBtn setTitle:@"login" forState:UIControlStateNormal];
    }
    return _loginBtn;
}

UserVM-ViewModel

@interface UserVM : NSObject

@property(nonatomic) NSString *username;
@property(nonatomic) NSString *pwd;
@property(nonatomic) NSString *headUrl;
@property(nonatomic) RACCommand *loginCommand;
@end

@interface UserVM()
{
    BOOL _result;
}
@property(nonatomic) RACSubject *loginSignal;
@end

@implementation UserVM

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

- (void)initParams{
    self.headUrl = @"red";
//    self.loginSignal = [[RACSubject alloc] init];
//    self.loginCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
//
//        [self loginWithUsername:self.username pwd:self.pwd callback:^(BOOL ret) {
//            if(ret){
//                [self.loginSignal sendNext:@"YES"];
//            }else{
//                [self.loginSignal sendError:nil];
//            }
//            [self.loginSignal sendCompleted];
//        }];
//        return self.loginSignal;
//    }];
    
    self.loginCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
        NSLog(@"in RACCommand block");
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            [self loginWithUsername:self.username pwd:self.pwd callback:^(BOOL ret) {
                if(ret){
                    [subscriber sendNext:@"YES"];
                }else{
                    [subscriber sendError:nil];
                }
                [subscriber sendCompleted];
            }];
            return nil;
        }];
    }];
}

//login
- (void)loginWithUsername:(NSString *)username pwd:(NSString *)pwd callback:(void(^)(BOOL ret))callback{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSLog(@"start login>>%@,%@",username,pwd);
        [NSThread sleepForTimeInterval:2];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            _headUrl = @"blue";
            _result = !_result;
            if(callback) callback(_result);
        });
    });
}
@end

TF:
usernameTf的值輸入直接同步到self.userVM的username
RAC(self.userVM,username) = self.usernameTf.rac_textSignal;
RAC(self.userVM,pwd) = self.pwdTf.rac_textSignal;

Btn:
通過(guò)RACCommand來(lái)與btn建立關(guān)系,點(diǎn)擊btn后的處理邏輯再VM內(nèi),然后VM把處理的結(jié)果反饋給VC
關(guān)聯(lián)btn點(diǎn)擊事件:
[[self.loginBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
[self.userVM.loginCommand execute:nil];
}];
事件處理后的反饋:
[self.userVM.loginCommand.executionSignals subscribeNext:^(RACSignal *x) {

    [x subscribeNext:^(id  _Nullable x) {
        NSLog(@"login succ>>>%@",x);
    }];
    [x subscribeCompleted:^{
        NSLog(@"login completed");
    }];
    [x subscribeError:^(NSError * _Nullable error) {
        NSLog(@"login errors>>>%@",x);
    }];
}];

頭像控件的關(guān)聯(lián):
VM內(nèi)調(diào)用登錄接口后,會(huì)獲取到用戶頭像url,如何做到在VM內(nèi)賦值了url后,VC內(nèi)的頭像控件就直接刷新呢:

[RACObserve(self.userVM, headUrl) subscribeNext:^(id  _Nullable x) {
        @strongify(self)
        NSLog(@"headUrl>>>%@",x);
        self.headImgV.backgroundColor = [UIColor redColor];
        if([x isEqualToString:@"blue"]){
            self.headImgV.backgroundColor = [UIColor blueColor];
        }
        
    }];

這樣改造后,你會(huì)發(fā)現(xiàn),數(shù)據(jù)處理與UI完全解耦了。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容