Mr. Crow
Mr. Crow

Reputation: 21

Reactive cocoa: Stop a RACSignal after UIViewController is dealloc

In my case, I presented a containerViewController consists of several UIViewControllers.

One of them, controller A, will send request to server every 10 seconds to get data. I used a RACSignal to do it:

[[[RACSignal interval:10 onScheduler:[RACScheduler mainThreadScheduler]] takeUntil:self.rac_willDeallocSignal] subscribeNext:DoSomeThing];

But when the containerViewController is dismissed from the rootViewController, the signal still fired every 10 seconds, means rac_willDeallocSignal of controller A is not called. How can it be fixed?????

Thanks!!!

Upvotes: 0

Views: 3744

Answers (2)

Sergii N.
Sergii N.

Reputation: 315

Maybe it is too late to answer this question, but yet it may be helpful for those who are looking for solution.

I have solved similar problem with creating separate signal when UIViewController will disappear, and used that signal as takeUntil: in the Interval signal. Code looks like this:

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    RACSignal *rac_viewWillDisappear = 
        [self rac_signalForSelector:@selector(viewWillDisappear:)];
    [[[RACSignal interval:10 onScheduler:[RACScheduler mainThreadScheduler]]
        takeUntil:rac_viewWillDisappear] subscribeNext:^(id x) {
            //Do what you need
    }];
}

Upvotes: 6

Dave Lee
Dave Lee

Reputation: 6489

The interval signal is infinite, it will never complete. Consequently, any objects that are strongly captured in the subscription blocks will also live on indefinitely, and thus their willDeallocSignal will not do anything. There are two ways to work around this:

  1. Capture objects weakly
  2. Explicitly dispose of the subscription

The first case is preferable. In this case, you could use @weakify(self) outside of the block and @strongify(self) inside the block.

The second option is more of a clumsy brute approach. I wouldn't recommend it.

See RAC's Memory Management.

Upvotes: 2

Related Questions