反应性可可避免在旗帜上观察以产生副作用

时间:2014-12-13 16:32:09

标签: ios reactive-cocoa

我试图了解如何在操作后避免使用标志来执行副作用。在我的代码中,我打开一个网络连接,之后,我设置代码以定期执行与服务器的心跳。当在这个连接上发送请求时,我需要重置心跳计时器,这就是我的代码看起来的样子 -

 (RACSignal *) connect: (NSString *) server {
     return [[MIConnection connect: server ] 
             doComplete {
              [self setupHeartBeat];

            }];
     }

  -(void) setupHeartBeat {
      [[[[[RACObserve (self, heartBeatReset) ignore@(NO)]

       map:^RACStream *(id value) {
           return [RACSignal interval:7
                        onScheduler:scheduler withLeeway:5]
                startWith:[NSDate date]]
        }]
        switchToLatest]
        flattenMap:^RACStream *(MIConnection * theConnection) {
           return [self sendHeartBeat] ;
       }]

        subscribeNext:^(id x) {
        self.heartBeatReset = NO;

         NSLog(@"Done with sending heartbeat");
     }];

    -(RACSignal *) sendRequest: (id) request {

     return [[MIConnection sendRequest: request ] 
             doComplete {
              self.heartBeatReset = YES;
            }];
     }

如您所见,我使用标志“heartBeatReset”来重置计时器以发送心跳。实现上述目标的更好方法是什么?感谢

1 个答案:

答案 0 :(得分:0)

可以使用空方法替换flag属性。然后-setupHeartBeat的实现可以在空方法上使用-rac_signalForSelector:,而不是在标志上使用RACObserve。调用空方法在语义上与将YES分配给标志相同。

- (void)resetHeartBeat {
}

- (RACSignal *)sendRequest:(id)request {
    return [[MIConnection sendRequest:request]
        doComplete {
            [self resetHeartBeat];
        }];
}

- (void)setupHeartBeat {
    RACSignal *heartBeatTimer = [[RACSignal
        interval:7 onScheduler:scheduler withLeeway:5]
        startWithDate:[NSDate date]];

    [[[[[self
        rac_signalForSelector:@selector(resetHeartBeat)]
        mapReplace:heartBeatTimer]
        switchToLatest]
        flattenMap:^(id _) {
            return [self sendHeartBeat];
        }]
        subscribe:nil];
}