- catch
Subscribes to the returned signal when an error occurs.
當(dāng)error發(fā)生時(shí)璧微,訂閱返回信號(hào)
可以理解為捕獲信號(hào)的error信息
RACSignal *signal = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
[subscriber sendNext:@"我是發(fā)送的信號(hào)"];
[subscriber sendError:[NSError errorWithDomain:@"www.huang"
code:0
userInfo:@{NSLocalizedDescriptionKey:@"錯(cuò)誤信息"}]];
return nil;
}];
RACSignal *newSignal = [signal catch:^RACSignal *(NSError *error) {
NSLog(@"%@",error.localizedDescription);
// 注意如果這里使用 [RACSignal return:error] newSignal就不會(huì)走error的回調(diào)了
return [RACSignal error:error];
}];
[newSignal subscribeNext:^(id x) {
NSLog(@"%@",x);
} error:^(NSError * error) {
NSLog(@"=%@",error.localizedDescription);
}];
***************
打印日志:
我是發(fā)送的信號(hào)
錯(cuò)誤信息
=錯(cuò)誤信息
- catchTo
Subscribes to the given signal when an error occurs.
catchTo
與 catch
相同的觸發(fā)場(chǎng)景,都需要訂閱者調(diào)用[subscriber sendError]
方法時(shí)东亦。
RACSignal *signal = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
[subscriber sendNext:@"我是發(fā)送的信號(hào)"];
// error occurs
[subscriber sendError:[NSError errorWithDomain:@"www.huang"
code:0
userInfo:@{NSLocalizedDescriptionKey:@"錯(cuò)誤信息"}]];
return nil;
}];
// RACSignal *newSignal = [signal catchTo:[RACSignal return:@(1122)]]; // 走next回調(diào)
RACSignal *newSignal = [signal catchTo:[RACSignal error:[NSError errorWithDomain:@"www.huang" code:0 userInfo:@{NSLocalizedDescriptionKey:@"catch的錯(cuò)誤信息"}]]]; // 走error回調(diào)
[newSignal subscribeNext:^(id x) {
NSLog(@"next:%@",x);
} error:^(NSError *error) {
NSLog(@"error:%@",error.localizedDescription);
}];
***************
打印日志:
next:我是發(fā)送的信號(hào)
error:catch的錯(cuò)誤信息
需要注意的是,當(dāng)調(diào)用catchTo
方法時(shí),是可以攔截next
回調(diào)或error
回調(diào)的银酗,取決于被catchTo
的信號(hào)。
- 源碼
- (RACSignal *)catch:(RACSignal * (^)(NSError *error))catchBlock {
NSCParameterAssert(catchBlock != NULL);
return [[RACSignal createSignal:^(id<RACSubscriber> subscriber) {
RACSerialDisposable *catchDisposable = [[RACSerialDisposable alloc] init];
RACDisposable *subscriptionDisposable = [self subscribeNext:^(id x) {
[subscriber sendNext:x]; //不會(huì)攔截原來(lái)的value徒像; 原來(lái)的信號(hào)變?yōu)闊嵝盘?hào)黍特,新信號(hào)被訂閱會(huì)來(lái)到這里
} error:^(NSError *error) {
RACSignal *signal = catchBlock(error); // 外界傳入的信號(hào)
NSCAssert(signal != nil, @"Expected non-nil signal from catch block on %@", self);
catchDisposable.disposable = [signal subscribe:subscriber];
} completed:^{
[subscriber sendCompleted];
}];
return [RACDisposable disposableWithBlock:^{
[catchDisposable dispose];
[subscriptionDisposable dispose];
}];
}] setNameWithFormat:@"[%@] -catch:", self.name];
}
- (RACSignal *)catchTo:(RACSignal *)signal {
return [[self catch:^(NSError *error) {
return signal; // 傳入的信號(hào)當(dāng)做新信號(hào)返回,所以訂閱新信號(hào)的結(jié)果決定于傳入的信號(hào)锯蛀!
}] setNameWithFormat:@"[%@] -catchTo: %@", self.name, signal];
}