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

岁酱吖の 提交于 2019-12-21 03:23:09

问题


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?


回答1:


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



回答2:


That might be helpful especially when you create nested subscriptions:

RACDisposable *subscription = [RACObserve(self, test) subscribeNext:^(id x) {
         NSLog(@"signal fired!");
}];
[subscription dispose];



回答3:


Little fix of kamil3 answer:

__block RACDisposable *subscription = [RACObserve(self, test) subscribeNext:^(id x) {
    [subscription dispose];
    NSLog(@"signal fired!");
}];



回答4:


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];
   }];
}];


来源:https://stackoverflow.com/questions/15615232/how-do-i-create-a-reactivecocoa-subscriber-that-receives-a-signal-only-once-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!