【发布时间】:2014-10-15 13:31:39
【问题描述】:
我在 ReactiveCocoa 世界中还是个新手,我只是想弄清楚这个常见的场景。我注意到其他人在 GitHub 和 SO 上都在努力解决这个问题,但我仍然缺少正确的答案。
以下示例确实有效,但我看到 Justin Summers 说订阅中的订阅或一般订阅可能是代码异味。因此,我想在学习这种新范式时尽量避免不良习惯。
因此,示例(使用 MVVM)非常简单:
- ViewController 包含一个登录按钮,该按钮连接到视图模型中的登录命令
- ViewModel 指定命令操作并模拟此示例的一些网络请求。
- ViewController 订阅命令的执行信号,并能够区分三种返回类型:下一个、错误和完成。
还有代码。
1(视图控制器):
RAC(self.loginButton, rac_command) = RACObserve(self, viewModel.loginCommand);
2(视图模型):
self.loginCommand = [[RACCommand alloc] initWithEnabled:canLoginSignal
signalBlock:^RACSignal *(id input) {
return [[RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
BOOL success = [username isEqualToString:@"user"] && [password isEqualToString:@"password"];
// Doesn't really make any sense to use sendNext here, but lets include it to test whether we can handle it in our viewmodel or viewcontroller
[subscriber sendNext:@"test"];
if (success)
{
[subscriber sendCompleted];
} else {
[subscriber sendError:nil];
}
// Cannot cancel request
return nil;
}] materialize];
}];
3(视图控制器):
[self.viewModel.loginCommand.executionSignals subscribeNext:^(RACSignal *execution) {
[[execution dematerialize] subscribeNext:^(id value) {
NSLog(@"Value: %@", value);
} error:^(NSError *error) {
NSLog(@"Error: %@", error);
} completed:^{
NSLog(@"Completed");
}];
}];
你会如何以更 ReactiveCococa 的方式来做到这一点?
【问题讨论】:
标签: ios objective-c reactive-cocoa