ios - ViewModel 完成操作时在 ViewController 中的通知

标签 ios objective-c reactive-cocoa

我正在制作一个简单的 iOS 应用程序以学习 ReactiveCocoa。到目前为止我一直在使用 XIB 文件,但决定切换到 Storyboard。 在我的第一个 View 中,我有登录屏幕,当用户按下按钮时,viewModel 执行 RACCommand 来验证用户并下载他的联系人列表。之后,我需要从 ViewController 调用 performSegueWithIdentifier: 来显示下载的数据。如何在 ViewController 中通知 viewModel 已成功完成其操作?

这是来自 ViewController 的代码片段:

RAC(self.viewModel, username) = self.usernameTextField.rac_textSignal;
RAC(self.viewModel, password) = self.passwordTextField.rac_textSignal;
self.loginButton.rac_command = self.viewModel.executeSignin;

以及来自其 ViewModel 的片段:

////////////////////////////////IN INIT////////////////////////////////////
self.executeSignin =
    [[RACCommand alloc] initWithEnabled:validAuthenticateSignal
                            signalBlock:^RACSignal *(id input) {
                                return  [self executeSigninSignal];
                            }];
//////////////////////////////////////////////////////////////////////////

-(RACSignal *)executpsigninsignal {
    return [[[self.services getAuthenticationService]
             authenticationSignalFor:self.username andPassword:self.password]
            //Return user if exists
            flattenMap:^RACStream *(STUser *user) {
                return [[[[[self services] getContactsLoadService]
                 contactsLoadSignalForUser:user] deliverOn:[RACScheduler mainThreadScheduler]]
                //Return user contacts
               doNext:^(NSArray *contacts) {
                   _downloadedContacts = [NSArray arrayWithArray:contacts];
               }];

            }];
}

我还尝试观察 ViewController 中的 ViewModels downloadedContacts 属性:

RACSignal *contactsLoadSignal = RACObserve(self.viewModel, downloadedContacts);
[[contactsLoadSignal filter:^BOOL(NSArray *value) {
    return value!=nil && value.count>0;
}]subscribeNext:^(NSArray *array) {
    [self performSegueWithIdentifier:@"pushContactsList" sender:self];
}];

但这似乎行不通,而且看起来也不太好。

最佳答案

您可以使用命令的 executionSignals 属性来做到这一点:

@weakify(self)
[executeSignin.executionSignals.switchToLatest filter:^BOOL(NSArray *value) {
    return value.count>0;  //nil check was redundant here
}] subscribeNext:^(NSArray *array) {
    @strongify(self)
    [self performSegueWithIdentifier:@"pushContactsList" sender:self];
}];

关于ios - ViewModel 完成操作时在 ViewController 中的通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35901825/

相关文章:

android - OpenMp 与 IOS/Android 的兼容性

ios - 方向更改后 UIView 消失

ios - 在 UILabels 后面设置背景相机

ios - 在后台线程中更新托管对象

ios - 如何在通知中使用 Reactive Cocoa

ios - react 性 cocoa : Response from HTTPRequest using RACCommand

ios - 如何在 Swift 中将 NSSet 转换为 NSMutableSet

iphone - 在视网膜和非视网膜屏幕上使用图像作为文本

ios - 发送数据包时核心蓝牙变慢

ios - ReactiveSwift/ReactiveCocoa : How to use UIButton disabled styling but not when Action is in progress?