简体   繁体   中英

ReactiveCocoa repeat command does not use modified values

I am trying to write a code that iterates forever, and here is how I have written it:

- (void) testRepeat {

__block DataClass * dc = [[DataClass alloc] init];    
[[[[self repeatFunc:dc ]      

  doNext:^(id x) {
     dc = nil;
  }]
  repeat]

  subscribeNext:^(id x) {
    NSLog(@"next");
 } completed:^{
    NSLog(@"completed");
 }];
}

- (RACSignal *) repeatFunc: (DataClass *) dc {

return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
    NSLog(@"dc : %@", dc);
    [subscriber sendNext:nil];
    [subscriber sendCompleted];
    return nil;

}];

}

The first time the code iterates, the value for object "dc" is correct. After the first call to repeatFunc, I am setting "dc" to nil, however, when it iterates back, the change in "dc" is not reflected and it is still the previous value.

What will be a correct way to achieve the above purpose?

The method -repeatFunc: captures an immutable reference to its own pointer to dc , and so each repeat sends that reference, not the local reference which you have nil 'd out.

It could be done like so:

__block DataClass *dc = [[DataClass alloc] init];
RACSignal *signal = [[[RACSignal
    defer:^{
        return [RACSignal return:dc];
    }]
    doNext:^(id x) {
        dc = nil;
    }]
    repeat];

But a more functional way to express this would be:

[[[RACSignal return:nil] repeat] startWith:dc];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM