我有以下代码贯穿一系列图像记录,尝试查找标记为“主要”的记录,加载并将其分配给UIImageView
:
// When there's a new image, fetch it, and set the headerView (which by default is an UIImageView)
RAC( self, imageView.image ) =
// Return a sequence for photos
[[[[[[self modelImagesSignal] ignore:nil] flattenMap:^RACStream *(NSDictionary *photos)
{
NSLog(@"Got photos: %@" , photos) ;
return photos.rac_sequence.signal ;
}]
// Consider each photo
filter:^BOOL(NSDictionary *photoDescriptor)
{
NSLog(@"Descriptor: %@" , photoDescriptor) ;
return ((NSNumber *)photoDescriptor[@"primary"]).boolValue ;
}]
// Load the selected photo
flattenMap:^RACStream *(NSDictionary *selectedPhotoDescriptor)
{
NSLog(@"selected photo desc: %@" , selectedPhotoDescriptor) ;
return [AsyncImageFetcher imageAtURL:[NSURL URLWithString:selectedPhotoDescriptor[@"url"]] cache:YES] ; // This will -deliverOn: the main thread
}]
// Catch errors
catch:^RACSignal *(NSError *error)
{
FLASH_REPORT_T(error.description, nil, xkFlashMessageTypeError) ;
return [RACSignal empty] ;
}] ;
我该怎么做?
答案 0 :(得分:3)
- 如果没有主要内容,我想返回遇到的第一条记录,无论是否是主要记录,
- 如果根本没有遇到任何记录,我想要返回默认图片。
醇>
这不是使用您的原始代码,而是提取您所要求的基本知识,这是一种组合信号以获得您想要的方法:
MyImageModel *myDefaultImageModel = [self createDefaultImageModel];
RACSignal *images = [self fetchImagesOrWhatever];
RACSignal *primaryImages = [images filter:^(MyImageModel *im) { return im.isPrimary; }];
RACSignal *defaultImage = [RACSignal return:myDefaultImageModel];
// This is the line to pay attention to:
RACSignal *finalImage = [[[primaryImages concat:[images concat:defaultImage]]] take:1];
RAC(self, imageView.image) = [finalImage map:^(MyImageModel *im) {
// Convert MyImageModel to a UIImage here, and return it.
}];
此代码按顺序构造一个名为finalImage
的信号,该信号由以下值组成:
然后使用-[RACSignal take:1]
来获取其中的第一个。如果#1或#2可能是空信号(因为没有原色或根本没有图像),你知道你至少会得到#3。