Help us understand the problem. What is going on with this article?

逆引きReactiveCocoa: NSNotificationのシグナルを終了させる

More than 5 years have passed since last update.

ReactiveCocoaにはNSNotificationの通知をRACSignal化するサポートがあり、

[[[NSNotificationCenter defaultCenter]
    rac_addObserverForName:UIApplicationDidEnterBackgroundNotification object:nil]
    subscribeNext:^(NSNotification *note) {
        // do something
    }];

という形で通知をシグナルのnextとして受け取ることができます。

しかしこれには一点注意しなければならないことがあります。というのも、-rac_addObserverForName:object:で得られるシグナルはcompletedになることがない無限のシグナル (Infinite Signal) であり、その一方で通知のオブサーバー登録の解除はシグナルが終了した時にしかされないため、上記のようなコードだとオブサーバー登録が解除されないままになってしまいます。

通常、ViewControllerでオブサーバー登録・解除を行う場合、以下のようなパターンになると思いますが、

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(someMethod:) name:name object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

それと同じことをする場合は下記のようなコードになります。

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[[[NSNotificationCenter defaultCenter]
        rac_addObserverForName:name object:nil]
        takeUntil:[self rac_signalForSelector:@selector(viewWillDisappear:)]]
        subscribeNext:^(NSNotification *note) {
            // do something
    }];
}

-takeUntil:に対して[self rac_signalForSelector:@selector(viewWillDisappear:)]とメソッド呼び出しに対応するシグナルを作用させることで、特定タイミングで元のシグナルを終了させ、結果的にオブサーバー登録が解除されるようになります。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした