11

尝试遵循 ReactiveCocoa 的最佳实践,每小时更新我的​​ UI。这就是我所拥有的:

NSDateComponents *components = [[[NSCalendar sharedCalendar] calendar] components:NSMinuteCalendarUnit fromDate:[NSDate date]];
// Generalization, I know (not every hour has 60 minutes, but bear with me).
NSInteger minutesToNextHour = 60 - components.minute;

RACSubject *updateEventSignal = [RACSubject subject];
[updateEventSignal subscribeNext:^(NSDate *now) {
    // Update some UI
}];

[[[RACSignal interval:(60 * minutesToNextHour)] take:1] subscribeNext:^(id x) {
    [updateEventSignal sendNext:x];
    [[RACSignal interval:3600] subscribeNext:^(id x) {
        [updateEventSignal sendNext:x];
    }];
}];

这有一些明显的缺陷:手动订阅和发送,它只是“感觉不对”。关于如何使其更具“反应性”的任何想法?

4

2 回答 2

20

您可以使用完全普通的运算符来做到这一点。只需将两个区间链接在一起,同时仍然通过它们的两个值,这正是-concat:所做的。

我将主题重写如下:

RACSignal *updateEventSignal = [[[RACSignal
    interval:(60 * minutesToNextHour)]
    take:1]
    concat:[RACSignal interval:3600]];

这可能不会为您提供超精确的精度(因为两个信号之间可能存在微小的打嗝),但对于任何 UI 工作来说,它应该足够 Good Enough™。

于 2013-05-14T05:37:33.947 回答
5

听起来你需要类似的东西+interval:startingIn:

有了这个想法,您可以+interval:startingIn:通过稍微调整.+interval:

+ (RACSignal *)interval:(NSTimeInterval)interval startingIn:(NSTimeInterval)delay {
  return [[RACSignal createSignal:^(id<RACSubscriber> subscriber) {

    int64_t intervalInNanoSecs = (int64_t)(interval * NSEC_PER_SEC);
    int64_t delayInNanoSecs = (int64_t)(delay * NSEC_PER_SEC);
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0));
    dispatch_source_set_timer(timer, dispatch_time(DISPATCH_TIME_NOW, delayInNanoSecs), (uint64_t)intervalInNanoSecs, (uint64_t)0);
    dispatch_source_set_event_handler(timer, ^{
      [subscriber sendNext:[NSDate date]];
    });
    dispatch_resume(timer);

    return [RACDisposable disposableWithBlock:^{
      dispatch_source_cancel(timer);
      dispatch_release(timer);
    }];
  }] setNameWithFormat:@"+interval: %f startingIn: %f", (double)interval, (double)delay];
}

有了这个,您的代码可以重构为:

NSDateComponents *components = [[[NSCalendar sharedCalendar] calendar] components:NSMinuteCalendarUnit fromDate:[NSDate date]];
// Generalization, I know (not every hour has 60 minutes, but bear with me).
NSInteger minutesToNextHour = 60 - components.minute;

RACSubject *updateEventSignal = [[RACSignal interval:3600 startingIn:(minutesToNextHour * 60)];
[updateEventSignal subscribeNext:^(NSDate *now) {
    // Update some UI
}];
于 2013-05-13T20:54:10.620 回答