学习RACCommand

一、理论

RACCommand 是ReactiveCocoa中比较复杂的类,可以用来创建个订阅响应某些事件的信号,在作用于与UIKit组件进行交互或者执行包含副作用的操作时,它能够帮助我们更快的处理并且响应任务,减少编码以及工程复杂度(😭),实现流程如下:

 

二、实践

ViewModel 文件里对外暴露RACCommand 属性,在init函数中初始化Raccommands

- (void)initRaccommands {
    @weakify(self);
    self.Command = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
        @strongify(self);
        return [self fetchFunc:input];
    }];
}
- (RACSignal*)fetchFunc:(id _Nullable)input {
    @weakify(self);
    RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        NSDictionary *params = @{};
        //网络请求事件
         [requestfunction doAction];
            
#warning -- 已选中的配置是否需要记忆回显
            
            [subscriber sendNext:response];
            [subscriber sendCompleted];
        } failure:^(NSError * _Nonnull error) {
            [subscriber sendError:error];
            [subscriber sendCompleted];
        }];
        return nil;
    }];
    return signal;
}

VC中订阅事件

 @weakify(self)
    [[self.ViewModel.carTypeCommand.executionSignals switchToLatest] subscribeNext:^(id  _Nullable x) {
        @strongify(self)
        //UI刷新操作
    }];
    [self.configViewModel.carTypeCommand.errors subscribeNext:^(NSError * _Nullable x) {
        //UI刷新操作
    }];

 

-switchToLatest 方法只能操作信号的信号

每次 executionSignals 中发送了新的信号时,switchToLatest 方法返回的信号都会订阅这个最新的信号,这里也就保证了每次都会打印出最新的信号中的值。

VC中 执行事件

[self.ViewModel.Command execute:nil];

 

参考资料

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值