一、理论
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];