RACCommand一般用來處理事件,監(jiān)聽按鈕點(diǎn)擊乡范,網(wǎng)絡(luò)請求等裁眯。
先看下RACCommand簡單使用
RACCommand的使用很簡單,就兩步
1:創(chuàng)建命令
RACCommand *command = [[RACCommand alloc]initWithSignalBlock:^RACSignal * _Nonnull(id _Nullable input) {
// 這里必須返回一個信號蠢终,不能返回為nil序攘,會崩潰
// 如果不想傳遞信號,可以發(fā)出空信號 [RACSignal empty];
// block調(diào)用時刻: [command execute:@1];
NSLog(@"請求網(wǎng)絡(luò)數(shù)據(jù)%@",input);
// 請求網(wǎng)絡(luò)數(shù)據(jù)完畢寻拂,怎么將網(wǎng)絡(luò)產(chǎn)生的數(shù)據(jù)發(fā)送出去呢程奠?
// 怎么發(fā)送? 就得靠下面這個RACSignal去發(fā)送祭钉,只要有人訂閱了RACSignal瞄沙,RACSignal數(shù)據(jù)就發(fā)送得出去
return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber> _Nonnull subscriber) {
[subscriber sendNext:@"發(fā)送網(wǎng)絡(luò)數(shù)據(jù)”];
//如果不再繼續(xù)發(fā)送數(shù)據(jù),要發(fā)送完成信號
[subscriber sendCompleted];
return nil;
}];
}];
2:執(zhí)行命令
[command execute:@1];
如何訂閱命令中的RACSignal信號呢?
有三種方法
- 方法一距境,最簡單的一種
你們查看 execute: 方法申尼,它返回的就是一個RACSignal
- (RACSignal *)execute:(id)input
所以,我們可以直接訂閱這個返回來的RACSignal
RACSignal *signal = [command execute:@1];
[signal subscribeNext:^(id _Nullable x) {
NSLog(@"%@",x);
}];
- 方法二垫桂,稍微復(fù)雜點(diǎn)
RACCommand 中有個屬性executionSignals师幕,它表示信號中的信號。
對了伪货,這里有個要注意的地方们衙,方法二必須要在執(zhí)行命令execute之前執(zhí)行
// 看打印結(jié)果可知,command.executionSignals 拿到的是一個RACSignal
[command.executionSignals subscribeNext:^(RACSignal * x) {
NSLog(@"%@",x); // x == RACDynamicSignal
[x subscribeNext:^(id _Nullable x) {
NSLog(@"%@",x);
}];
}];
[command execute:@1];
- 方法三碱呼,高級用法
switchToLatest 獲取最新發(fā)送的信號蒙挑,只能用于信號中的信號
[command.executionSignals.switchToLatest subscribeNext:^(id _Nullable x) {
NSLog(@"%@",x);
}];
[command execute:@1];
RACCommand還有一個比較好用的屬性,executing愚臀,它用來監(jiān)聽事件有沒有完成
比如:當(dāng)你點(diǎn)擊一個按鈕訪問網(wǎng)絡(luò)的時候忆蚀,你總不能每次點(diǎn)的時候都訪問網(wǎng)絡(luò)吧,肯定要等網(wǎng)絡(luò)處理完成之后才能繼續(xù)點(diǎn)姑裂,這個時候馋袜,你就可以用到這個屬性
// executing 直接返回一個 RACSignal
@property (nonatomic, strong, readonly) RACSignal<NSNumber *> *executing;
// 監(jiān)聽事件有沒有完成,
[command.executing subscribeNext:^(NSNumber * _Nullable x) {
if ([x boolValue] == YES) {
NSLog(@"當(dāng)前正在執(zhí)行");
}
else {
NSLog(@"執(zhí)行完成/沒有執(zhí)行");
}
}];