LoginSignup
9
9

More than 5 years have passed since last update.

逆引きReactiveCocoa: シグナルにイベント発生時に対する処理を挟み込む

Last updated at Posted at 2013-12-05

ReactiveCocoaのドキュメントにもあるように、-do...系のメソッドを使用すると、シグナルを購読せずに副作用を挟み込むことができます。

RACSignal *newSignal = [[[signal 
    doNext:^(id x) {
        NSLog(@"next");
    }] 
    doError:^(NSError *error) {
        NSLog(@"error");
    }] 
    doCompleted:^{
        NSLog(@"completed");
    }];

シグナルを購読する終端であれば、各種処理を-subscribe...:系のメソッドのブロック内で行うこともできますが、シグナルに手を加えてシグナルを返すようなメソッドでは便利に使用することができます。

また、例えば-doNext:を重ねて記述した場合、記述順(lexical order)に処理が実行されます。

[[[signal
    doNext:^(id x) {
        NSLog(@"1st");
    }]
    doNext:^(id x) {
        NSLog(@"2nd");
    }]
    subscribeNext:^(id x) {
        NSLog(@"-subscribeNext:");
    }];
// 1st
// 2nd
// -subscribeNext:

シグナルの終了時の処理として正常系/異常系のどちらでも同じ処理を行いたい場合、-finally:が使用できます。

// 以下の2つは同義。

[signal finally:^{
    [self doSomeStuff];
}];

[[signal
    doError:^(NSError *error) {
        [self doSomeStuff];
    }]
    doCompleted:^{
        [self doSomeStuff];
    }];

補足

ReactiveCocoa 3.0では-finally:は非推奨となり、-doFinished:が追加(としてリネーム)されています。

9
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
9