RACCommand封装网络请求(配合猿题库)

2020-12-23  本文已影响0人  下班不写程序

1. 便于理解的使用方法

@property (nonatomic, copy) NSString *username;

@property (nonatomic, copy) NSString *password;

@property (nonatomic, strong) RACCommand *loginButtonCommand;
- (instancetype)init {
    self = [super init];
    if (self) {
        
        RACSignal *usernameSingal = [RACObserve(self, username) map:^id _Nullable(id  _Nullable value) {
            
            if ([(NSString *)value length] > 6) {
                return @(YES);
            } else {
                return @(NO);
            }
        }];
        
        RACSignal *passwordSingl = [RACObserve(self, password) map:^id _Nullable(id  _Nullable value) {
            
            if ([(NSString *)value length] > 6) {
                return @(YES);
            } else {
                return @(NO);
            }
        }];
        
        RACSignal *loginSingl = [RACSignal combineLatest:@[usernameSingal, passwordSingl] reduce:^id (NSNumber *username, NSNumber *password){
            return @([username boolValue] && [password boolValue]);
        }];
        
        self.loginButtonCommand = [[RACCommand alloc] initWithEnabled:loginSingl signalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
            return [self loginWithUserName:self.username password:self.password];
        }];
    }
    return self;
}

- (RACSignal *)loginWithUserName:(NSString *)name password:(NSString *)passWord {
    
    return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        [subscriber sendNext:[NSString stringWithFormat:@"姓名:%@ 密码:%@",self.username, self.password]];
        [subscriber sendCompleted];
        return nil;
    }];
}

定义vm属性

@property (nonatomic, strong) LoginViewModel *viewModel;

绑定信号

    self.LoginButton.rac_command = self.viewModel.loginButtonCommand;
    RAC(self.viewModel, username) = self.usernameTextfield.rac_textSignal;
    RAC(self.viewModel, password) = self.passwordTextfield.rac_textSignal;

登录点击事件

    [[self.viewModel.loginButtonCommand executionSignals] subscribeNext:^(id  _Nullable x) {
       
        [x subscribeNext:^(id  _Nullable x) {
            NSLog(@"%@",x);
        }];
    }];

以上就是最简单的使用方法了

2. 结合猿题库网络请求框架

可参见demo

  1. ViewMode内容


    ViewMode.h ViewMode.m 控制器中使用

.End

上一篇 下一篇

猜你喜欢

热点阅读