How do I create a ReactiveCocoa subscriber that receives a signal only once, then unsubscribes/releases itself?
Asked Answered
E

4

17

I'm currently registering a subscriber to a property signal like this:

[RACAble(self.test) subscribeNext:^(id x) {
        NSLog(@"signal fired!");
 }];

The default functionality is that it fires every single time self.test is changed, but I just want it to fire once, and then unsubscribe. Is there a "once" argument or modifier I can pass to RAC when I create this subscriber?

Emunctory answered 25/3, 2013 at 12:40 Comment(0)
U
32
[[RACAble(self.test) take:1] subscribeNext:^(id x) {
    NSLog(@"signal fired!");
}];
Ulmer answered 25/3, 2013 at 17:37 Comment(1)
thanks, this prompted me to refactor a couple of signal generating methods into something much more sane.Kris
F
0

That might be helpful especially when you create nested subscriptions:

RACDisposable *subscription = [RACObserve(self, test) subscribeNext:^(id x) {
         NSLog(@"signal fired!");
}];
[subscription dispose];
Ferromagnetic answered 27/7, 2016 at 18:31 Comment(0)
R
0

Little fix of kamil3 answer:

__block RACDisposable *subscription = [RACObserve(self, test) subscribeNext:^(id x) {
    [subscription dispose];
    NSLog(@"signal fired!");
}];
Ravid answered 21/6, 2019 at 13:19 Comment(0)
K
-1

you can also do this (if you aren't into the whole brevity thing):

[RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber){
   RACDisposable *inner_disposer = [RACAble(self.test) subscribeNext:^(id x){
      [subscriber sendNext:x];
      [subscriber sendComplete];
   }];
   return [RACDisposable disposableWithBlock:^{
      [inner_disposer dispose];
   }];
}];
Kris answered 1/8, 2013 at 12:12 Comment(1)
There's no reason to use this over take:1, and it can introduce subtle bugs (like the retain cycle on self).Pinxit

© 2022 - 2024 — McMap. All rights reserved.