![](/img/trans.png)
[英]Reactive cocoa issue.How to wait mutiple RACSignal completed then send a next signal
[英]how to wait until the task is completed and then return a signal, reactive cocoa
-(RACSignal*)finalPackage {
RACSignal *endPoint = [[DGConfiguration sharedInstance].apiConfiguration
urlTemplate:DGAPIUrlLocalWatchList];` // 1.
return [[endPointRequestSignal map:^id(NSString *endPoint) { // 2.
return service([NSURL URLWithString: endPoint]);
}].flatten map:^id(NSArray *episodes) { // 3.
NSMutableArray *info= [NSMutableArray array];
__block NSArray *result=@[@(9)]; // test value is 9, result will be updated during callback block
[episodes enumerateObjectsUsingBlock:^(NSDictionary *item, NSUInteger idx, BOOL *stop) {
[info addObject:@{@"id":item[@"id"],@"links":item[@"links"]}];
}];
[[DGManager sharedInstance] updateVideoStateWith:info callback:^(NSArray *response) { // 4.
dispatch_async(dispatch_get_main_queue(), ^{
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"timeStamp" ascending:NO];
result = [[response sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]] copy];
});
}];
return [RACSignal return:result]; // 5.
}].flatten;
}
讓我解釋一下我要做什么。
endPoint
信號包裝endPoint url map
提取URL並進行服務調用( service([NSURL URLWithString: endPoint])
) map
從步驟2中提取信息並創建info
數據 updateVideoStateWith
result
的信號 最終,當我訂閱finalPackage
信號時,返回的初始化值為9
我意識到, updateVideoStateWith
回調將花費一些時間來返回結果。
我的問題是如何強制return [RACSignal return:result]
等到從回調塊更新數據。 我確實嘗試過takeUntilBlock,但不確定如何使用它。 我也考慮使用switchToLatest,但還是沒有運氣。
從GitHub問題交叉發布我的答案:
- (RACSignal*)finalPackage {
return [RACSignal createSignal:^(id<RACSubscriber> subscriber) {
RACSignal *endPointSignal = [[DGConfiguration sharedInstance].apiConfiguration urlTemplate:DGAPIUrlLocalWatchList];
[[endPointSignal map:^id(NSString *endPoint) {
// map your endpoints to episodes and return the array of episodes
}] subscribeNext:^(NSArray* episodes) {
// Create your initial result array
[[DGManager sharedInstance] updateVideoStateWith:info callback:^(NSArray *response) {
// Do whatever work you need to do with the response to modify the result array
[subscriber sendNext:result];
[subscriber sendComplete];
}];
} error:^(NSError* error) {
[subscriber sendError:error];
]];
return nil;
}];
}
注意:如果從endPoint NSString映射時返回RACSignal *,則需要用flattenMap
代替map
,flattenMap將把返回的信號展平為它發出的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.