链接在ReactiveCocoa有关的信号(Chaining dependent signals i

2019-08-19 08:08发布

在ReactiveCocoa,如果我们链接几个有关的信号,必须用subscribeNext:对于所述链中的下一个信号接收所产生的值之前的信号(例如,异步操作的结果)。 因此,一段时间后,代码变成这样的事情(被省略不必要的细节):

RACSignal *buttonClickSignal = [self.logIn rac_signalForControlEvents:UIControlEventTouchUpInside];

[buttonClickSignal subscribeNext:^(UIButton *sender) {    // signal from a button click
    // prepare data

    RACSignal *loginSignal = [self logInWithUsername:username password:password];    // signal from the async network operation

    [loginSignal subscribeNext:^void (NSDictionary *json) {
        // do stuff with data received from the first network interaction, prepare some new data

        RACSignal *playlistFetchSignal = [self fetchPlaylistForToken:token];         // another signal from the async network operation

        [playlistFetchSignal subscribeNext:^(NSDictionary *json) {
            // do more stuff with the returned data
        }];

        // etc
    }];
}];

这种不断增加的嵌套看起来并不比在文档中给出的非活性例如好得多:

[client logInWithSuccess:^{
    [client loadCachedMessagesWithSuccess:^(NSArray *messages) {
        [client fetchMessagesAfterMessage:messages.lastObject success:^(NSArray *nextMessages) {
            NSLog(@"Fetched all messages.");
        } failure:^(NSError *error) {
            [self presentError:error];
        }];
    } failure:^(NSError *error) {
        [self presentError:error];
    }];
} failure:^(NSError *error) {
    [self presentError:error];
}];

我缺少的东西吗? 是否有ReactiveCocoa链相关的工作更好的模式?

Answer 1:

这是当RACStream和RACSignal运营商开始派上用场真的来了。 在您的具体的例子,你可以用-flattenMap:纳入结果纳入新的信号:

[[[buttonClickSignal
    flattenMap:^(UIButton *sender) {
        // prepare 'username' and 'password'
        return [self logInWithUsername:username password:password];
    }]
    flattenMap:^(NSDictionary *json) {
        // prepare 'token'
        return [self fetchPlaylistForToken:token];
    }]
    subscribeNext:^(NSDictionary *json) {
        // do stuff with the returned playlist data
    }];

如果你不需要从任何一个步骤的结果,你可以使用-sequenceMany:-sequenceNext:不是有同样的效果(但意图更清晰的表达)。



文章来源: Chaining dependent signals in ReactiveCocoa