首先,您需要一个执行异步操作的包装方法,该方法将返回一个信号。我们假设异步操作需要一个完成块。从它的声音来看,您不关心这些值,您想要副作用,在这种情况下信号不会发送值,它只会完成。
- (RACSignal *)asyncOperation {
return [RACSignal createSignal:^RACDisposable * (id<RACSubscriber> subscriber) {
[self asyncOperationWithCompletion:^{
[subscriber sendCompleted];
}];
return nil; // `nil` means there's no way to cancel.
}];
}
编辑:感谢 Justin Spahr-Summers 的评论,这里有一个更简单的链接操作的方法:
RACSignal *signal = [RACSignal concat:[array.rac_sequence map:^(id entity) {
return [entity asyncOperation];
}]];
活性可可+concat:
运算符获取一组信号并一次订阅一个信号,等待一个信号完成后再订阅其后继信号。使用-rac_sequence
这里的目的是将实体映射到操作信号。
在这种情况下,使用+concat:
达到同样的效果-then:
从我下面最初的答案开始。
使用 RAC 包装器,解决方案是从空信号开始,通过迭代实体并使用以下方法组装操作来构建链:-then: https://github.com/ReactiveCocoa/ReactiveCocoa/blob/f9bc1fd2c58e0c5f9096a1c42d3e51d9c912d4e0/ReactiveCocoaFramework/ReactiveCocoa/RACSignal+Operations.h#L196-205. The -then:
操作本质上是等待上一个操作完成后再开始下一个操作。
RACSignal *signal = [RACSignal empty];
for (id entity in array) {
signal = [signal then:^{
return [entity asyncOperation];
}];
}
[signal subscribeCompleted:^{
// At this point, all operations have completed
}];
此时你所拥有的是:
[[[[RACSignal empty]
then:^{ return [entity1 asyncOperation]; }]
then:^{ return [entity2 asyncOperation]; }]
// ...
then:^{ return [entityN asyncOperation]; }]
ReactiveCocoa 有帮助文档 https://github.com/ReactiveCocoa/ReactiveCocoa/tree/master/Documentation以及记录良好的标题,当我还是新手时,这两者都非常有价值。