最近在学JS,发现使用JS的Promise写多个异步请求不需要嵌套,挺友好。所以就想研究下OC有没对应的方式。
OC的话可以通过ReactObj这个库来实现。ReactObj主要是为了实现MVVM而生的,通过信号控制一切。
1、先定义三个异步请求函数
接口2依赖接口的结果,接口3依赖接口2的结果。
//接口1
- (void)fetchData1:(void(^)(BOOL ret, NSString *userid))callBack{
dispatch_async(dispatch_get_global_queue(0, 0), ^{
[NSThread sleepForTimeInterval:2];
dispatch_async(dispatch_get_main_queue(), ^{
if(callBack) callBack(YES,@"65432");
});
});
}
//接口2依赖接口1返回的userid
- (void)fetchData2:(NSString *)userid callBack:(void(^)(BOOL ret,NSString *userid))callBack{
dispatch_async(dispatch_get_global_queue(0, 0), ^{
[NSThread sleepForTimeInterval:1];
dispatch_async(dispatch_get_main_queue(), ^{
if(callBack) callBack(YES,@"00000");
});
});
}
//接口3依赖接口2的结果
- (void)fetchData3:(NSString *)userid callBack:(void(^)(BOOL ret))callBack{
dispatch_async(dispatch_get_global_queue(0, 0), ^{
[NSThread sleepForTimeInterval:2];
dispatch_async(dispatch_get_main_queue(), ^{
if(callBack) callBack(NO);
});
});
}
2、把三个接口转换成signal
- (RACSignal *)creatFetchData1Signal{
NSLog(@"start fetchData1");
return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber> _Nonnull subscriber) {
[self fetchData1:^(BOOL ret, NSString *userid) {
if(ret){
[subscriber sendNext:userid];
}else{
[subscriber sendError:nil];
}
[subscriber sendCompleted];
}];
return nil;
}];
}
- (RACSignal *)creatFetchData2Signal:(NSString *)userid{
NSLog(@"start fetchData2 param>>>>%@",userid);
return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber> _Nonnull subscriber) {
[self fetchData2:userid callBack:^(BOOL ret, NSString *userid) {
if(ret){
[subscriber sendNext:userid];
}else{
[subscriber sendError:nil];
}
[subscriber sendCompleted];
}];
return nil;
}];
}
- (RACSignal *)creatFetchData3Signal:(NSString *)userid{
NSLog(@"start fetchData3 param>>>>%@",userid);
return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber> _Nonnull subscriber) {
[self fetchData3:userid callBack:^(BOOL ret) {
if(ret){
[subscriber sendNext:@(ret)];
}else{
[subscriber sendError:nil];
}
[subscriber sendCompleted];
}];
return nil;
}];
}
3、使用signal
[[[[self creatFetchData1Signal] flattenMap:^__kindof RACSignal * _Nullable(id _Nullable value) {
return [self creatFetchData2Signal:value];
}]flattenMap:^__kindof RACSignal * _Nullable(id _Nullable value) {
return [self creatFetchData3Signal:value];
}]subscribeNext:^(id _Nullable x) {
NSLog(@"ret==%@",x);
} error:^(NSError * _Nullable error) {
NSLog(@"error");
} completed:^{
NSLog(@"completed");
}];