flattenMap的重要性2:
// 网络操作的简单思路
RACSignal *signal = [RACSignal return:@"https://www.baidu.con"];
RACSignal *getSignal = [signal flattenMap:^RACStream *(id value) {
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:value]];
return [NSURLConnection rac_sendAsynchronousRequest:request];
}];
RACSignal *jsonSignal = [getSignal flattenMap:^RACStream *(NSData *data) {
NSError *error = nil;
id result = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
return error == nil ? [RACSignal return:result] : [RACSignal error:error];
}];
RACSignal *getItemSignal = [jsonSignal flattenMap:^RACStream *(id value) {
if (![value isKindOfClass:[NSDictionary class]] || value[@"data.url"] == nil) {
return [RACSignal error:[NSError errorWithDomain:@"0" code:0 userInfo:nil]];
}
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:value[@"data.url"]]];
return [NSURLConnection rac_sendAsynchronousRequest:request];
}];
}
网友评论