我想知道用反应性可可检查nil值的方法是什么。
我认为我可以创建一个这样的信号。
// Turn state check into a signal to activate the rest
RACSignal* modelSignal = [self checkIfModelIsValid:self.model];
[[modelSignal then:^RACSignal *{
return [self obtainImageSignal];
// Always need to lazy call these functions
}]
subscribeNext:^(id x) {
NSLog(@"It worked out! giving you null for fun though feel free to chain it? %@",x);
}
error:^(NSError *error) {
// Replace with real ns error
NSLog(@"Model or picture is nil: %@",error);
}
completed:^{
NSLog(@"Model this event started it all");
}];
-(RACSignal *)obtainImageSignal {
@weakify(self)
RACSignal* imageSignal = [[NetworkManager sharedInstance] getImageWithImagePath:self.model.fullSizedPicture];
// Processes that image signal
[[imageSignal deliverOn:[RACScheduler mainThreadScheduler]]
subscribeNext:^(UIImage* image) {
@strongify(self)
self.imageView.image = image;
[self setUpTitle:self.model.title];
[self setUpDescription:self.model.imageDescription];
}
error:^(NSError* error) {
NSLog(@"Error: %@",[error description]);
}
completed:^{
NSLog(@"Completed Operation: Image Retrieval Operation");
}];
return imageSignal;
}
-(RACSignal *) checkIfModelIsValid:(PhotoModel*) model {
// Using then on this signal will force the image signal to handle the errors.?
return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
if (self.model == nil || self.model.fullSizedPicture == nil) {
[subscriber sendError:nil];
}
else {
[subscriber sendNext:[NSNumber numberWithBool:YES]];
[subscriber sendCompleted];
// send complete for fun and see what it does
}
return nil;
}];
}
或者是否理智检查不适用于对函数式编程做出反应?
答案 0 :(得分:0)
为了给其他观众提供一个示例,一种确保您不从nil
模型中获取任何图像的方法 - 可以执行以下操作:
RAC(self.someImageView, image) = [[RACObserve(self, model)
filter:^BOOL(PhotoModel *currentModel) {
return currentModel != nil;
}]
map:^id(PhotoModel *currentModel) {
return [self someMethodToDownloadImageFromModel:currentModel];
}];
请注意我是如何避免在我的RAC块中使用self
并避免注入使用subscribeNext:^
,then:^
等时出现的副作用。通过这种方式,您的代码可以更轻松地管理和更多RAC。