我想在 iOS 中使用Reactive Cocoa实现倒数计时器。计时器应该运行 X 秒并每秒执行一些操作。我无法弄清楚的部分是我可以取消 timeout的方式。
RACSubscribable *oneSecGenerator = [RACSubscribable interval:1.0];
RACDisposable *timer = [[oneSecGenerator take:5] subscribeNext:^(id x) {
NSLog(@"Tick");
}];
我想在 iOS 中使用Reactive Cocoa实现倒数计时器。计时器应该运行 X 秒并每秒执行一些操作。我无法弄清楚的部分是我可以取消 timeout的方式。
RACSubscribable *oneSecGenerator = [RACSubscribable interval:1.0];
RACDisposable *timer = [[oneSecGenerator take:5] subscribeNext:^(id x) {
NSLog(@"Tick");
}];
我想,我找到了解决方案。诀窍是将取消信号合并到滴答信号中,然后取 X 个样本。最终订阅者将在每次滴答信号滴答声时收到下一个事件,并在“获取”完成时完成。取消可以通过在取消定时器上发送错误来实现。
__block RACSubject *cancelTimer = [RACSubject subject];
RACSubscribable *tickWithCancel = [[RACSubscribable interval:1.0] merge:cancelTimer];
RACSubscribable *timeoutFiveSec = [tickWithCancel take:5];
[timeoutFiveSec subscribeNext:^(id x) {
NSLog(@"Tick");
} error:^(NSError *error) {
NSLog(@"Cancelled");
} completed:^{
NSLog(@"Completed");
[alert dismissWithClickedButtonIndex:-1 animated:YES];
}];
要激活取消,必须执行以下操作。
[cancelTimer sendError:nil]; // nil or NSError
还有一个TakeUntil 操作符,它完全符合您的要求:中继来自流的事件,直到另一个产生值。